Pass clicked element' s attributes in another function - javascript

Hello guys I try to figure out how can I pass an element's attributes which I clicked in a different function
To be specific I have a dozen of elements with the same className = online
However each of the elements has one unique id which I assigned to them dynamically.
I use $(document).on because I want to listen on the document, for a click because the elements with className=online are created dynamically too.
$(document).on("click", ".online", isInPrivateChat);
How can I then in a different function for example
function TakeTheidfTheElement(){
//take the id of the element i clicked
}
I know I should use jquery method .attr('id') but cant really make it work.
Thanks

Working fiddle.
You could simply get the id from the callback function isInPrivateChat using this.id like :
function isInPrivateChat(){
alert( this.id );
}
Hope this helps.
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(){
console.log( this.id );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='online' id='id_1'>Btn 1</button>
<button class='online' id='id_2'>Btn 2</button>
<button class='online' id='id_3'>Btn 3</button>

Carry the ID through:
$(document).on("click", ".online", function() {
isInPrivateChat($(this).attr('id')); /* <-- get id and pass it in */
});
then
function TakeTheidfTheElement(idPassed){
// do something with idPassed
}
For the record, Zacaria's answer is the better option - showing this is how you can use .attr('id')

You can pass the whole element to a sub function and there you can use JQuery or straight javascript to get the properties of the element.
$(document).on("click",".online",function() {
getMyId(this);
});
function getMyId(element) {
alert(element.id);
}
If you just wanted to pass the id through to the sub function you can do:
$(document).on("click",".online",function() {
getMyId(this.id);
});
function getMyId(elementID) {
alert(elementID);
}
Here's a fiddle of it working

check the below code snippet
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(event) {
anotherFunctin(event.currentTarget.id);
}
function anotherFunctin(id){
console.log(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="online" id="id">
click me
</div>

Related

get id of button by clicked with function

html
<button id="test1" onclick="getclickname(); return false;">click</button>
javascript (it's showing "Undefined")
function getclickname()
{
alert(this.id);
}
i dont want code like this
<button id="test1" onclick="alert(this.id);">click</button>
call getclickname is needed, thanks guys
You have to pass corresponding argument to the function.
You need to pass button object to onclick function to get the id of button.
function getclickname(obj)
{
//By passing object as argument you can access all properties of that element
alert(obj.id);
alert(obj.className);
}
<button id="test1" onclick="getclickname(this); return false;" class="test_1">click</button>
You can directly pass this.id as well as an argument
function getclickname(id) {
alert(id);
}
<button id="test1" onclick="getclickname(this.id); return false;">click</button>
Note:
A bit code modification is instead of return false; you can add return before function name and that will do the same thing. like :- onclick="return getclickname(this.id);"
By passing object as argument you can access all properties of that element (check first code sample modification).
Hope this Helpful...
view
onclick="return getclickname(this);"
js
function getclickname(these)
{
alert(these.id);
}
Please try the below code. It's working for you.
Use class for click event in button.
<button id="test1" class="test-btn" >click</button>
Use the below click event function to get id after click.
$('.test-btn').click(function() {
var id = $(this).attr('id');
alert(id)
});
Use like this
<button id="test1" onclick="getclickname(this); return false;">click</button>
<script>
function getclickname(e)
{
alert(e.id);
}
</script>

changing class name and sending parameter in javascript

I would like to change the class of a tag and send a parameter i to the myFunction the tag is without id or name:
<a class="active" onclick="myFunction('i')"></a>
<script>
function myFunction(obj) {
}
</script>
using this in the function like myFunction(this,'i') doesn't work.
using this in the function like myFunction(this,'i') doesn't work.
That should work, you just need to amend the function to accept the element as an argument.
However you should note that on* event attributes are massively outdated and should be avoided where possible. Use unobtrusive event handlers instead:
Array.from(document.querySelectorAll('a.active')).forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
console.log(this.dataset.foo);
});
});
One
Two
Three
Update:
You mentioned in the comments that you're going to use jQuery AJAX, so you can simplify above with jQuery:
$('a.active').click(function(e) {
e.preventDefault();
console.log($(this).data('foo'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
One
Two
Three
You can do something like this:
function myFunction(obj) {
var data = obj.attr("data-param");
obj.removeClass("active");
alert(data);
}
$(document).ready(function(){
$(".test").on("click", function(){
myFunction($(this))
});
});
<a class="test active" href="javascript:void(0);" data-param="i">test</a>
Fiddle:
https://jsfiddle.net/u81g6qk4/10/
You can pass a reference to an HTML element by putting this is the function. Then you can use the element reference to do stuff to it without needing a id or name attribute.
someOtherClass is an assumed variable that contains the name of the class you want to add. Change it to whatever class or variable you want to use.
<a class="active" onclick="myFunction(this, 'i')"></a>
<script>
function myFunction(obj, param2) {
$(obj).removeClass("active");
$(obj).addClass(someOtherClass);
}
</script>
Use this if you do not want to use Jquery
<a class="active" onclick="myFunction(this, 'i')">Click Me</a>
<script>
function myFunction(element, str) {
console.log(str);
element.setAttribute('class', 'clicked');
}
</script>

How to pass a argument from anchor tag onclick to a function inside document.ready

Suppose I have a function inside document ready.
$(document).ready(function()
{
function myFunction(id) {
alert(id);
};
})
I want to pass an argument from an anchor tag like that.
Item 1
Item 2
Item 3
I know myFunction is not in global scope. That is why it will not going to work. So is there any way to pass an argument from anchor tag to a function inside document ready?
Try using jQuery event binding.
$(document).ready(function()
{
function myFunction(id) {
alert(id);
};
$(document).on("click", "a", function(event) {
var arg = $(this).attr("data-arg");
myFunction(arg);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Item 1
Item 2
Item 3
There's no need to put the function in document.ready, that would only be needed if you need to get an element from the DOM for your selector to find it.
So either omit that, or do it the proper way and assign an event listener and handler. To pass different things from your <a>, you could use a data-attribute, for example.
$(document).ready(function()
{
$('a').on('click', function(e) {
e.preventDefault();
console.log($(this).data('foo'));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Item 1
Item 2
Item 3

Getting element id with jquery

The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML
<body>
<div id="form_area">
<div>
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
</body>
Javascript
$(document).ready(function() {
$('#form_area div').click(function(e) {
console.log($(this).attr('id'));
});
});
function add_row() {
var random_id = Math.floor((Math.random() * 1000) + 1);
$('#form_area').prepend('<div id="' + random_id + '" class="form_row"></div>');
}
Ok, I think I understand what you are missing. You are trying to log the ID after adding a row using add_row function,
.form_row is added dynamically to the DOM. So when executing $('.form_row').click(, there is no .form_row to bind the handler. The below way of using .on method binds the handler to #form_area and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
$('#form_area div') selects the div inside the div #form_area which doesn't have an ID
Below comment in html shows which div is selected,
<div id="form_area">
<div> <!-- $('#form_area div') selects this div-->
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
To access id use 'on' as your div is dynamically generated:
$(document).ready(function() {
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
});
Try console.log($('#form_area div').attr('id'));
Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.
Secondly, your button handler is inside #formarea and so is also triggering the click handler since the button's parent has no ID. This is probably not desired.
Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.
So, remove the onclick attribute and add this:
$('#formarea button').on('click', addRow);
$('#formarea').on('click', '.form_row', function() { // delegated, for dynamic rows
console.log(this.id); // NB: not $(this).attr('id') !!
});
function addRow(ev) {
// unmodified
}
See http://jsfiddle.net/alnitak/aZTbA/

passing a parameter with onclick function is read as a variable when it should be read as a string

Here is my issue:
I am creating dynamically a button with an onclick function like this:
$("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');
The parameters are well read but the function is not trigger, and I've got this error message:
"bob is not defined" when bob is the string value of the param1.
Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.
Thanks much for your help!
That's because this string right here:
'onclick="remove('+param1+','+param2+');"'
Will look like this in the end:
'onclick="remove(foo, bar);"'
You probably want it to look like this:
'onclick="remove(\'foo\', \'bar\');"'
So change it to this:
'onclick="remove(\''+param1+'\', \''+param2+'\');"'
You could also do this:
$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
remove(param1, param2);
});
Edit: I also noticed that you were missing one " from your $()-call: $("#test) should be $("#test").
I can suggest you this
<script type="text/javascript">
//<![CDATA[
var i = 0;
$(function () {
$("#lnkAdder").click(function () {
// appending new item
$("#Container").append(
$("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
var data = ++i;
alert("I'm clicked, I'm number " + data);
})
);
});
});
//]]>
</script>
Add item
<div id="Container"></div>
The key here is the javascript closure.
As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.

Categories