I have a function that is called in an onclick event in a checkbox field.
<input type='checkbox' checked='' onclick='return changeEnable();' id='someid'>
and the function
function changeEnable()
{
var val = $(this).attr('id');
alert(val);
}
I have that but it returns undefined
. Is my syntax wrong or did I miss something?
Those checkboxes are dynamically created and have different id's, that's why I want to get the id for some task.
Once you have located your inspect element tool, right click on the element and click Inspect Element. It will bring up the element ID.
The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document.
The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.
Note that this
in your changeEnable
function will be the window
. You need to pass the reference to the element as a parameter to the function:
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>
function changeEnable(el) {
var val = el.id
alert(val);
}
Or, as an improvement, use Javascript to attach your events for a better separation of concerns:
<input type="checkbox" id="someid">
$(function() {
$('#someid').change(function() {
var val = this.id
alert(val);
}
});
Note that the above uses the change
event of the checkbox, which is better for accessibility reasons.
i think this code will help u a lot
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>`
function changeEnable(thisobj)
{
var val = thisobj.id;
alert(val);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With