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.
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.
Share Improve this question edited Jul 2, 2015 at 10:13 Nanne 64.4k16 gold badges122 silver badges166 bronze badges asked Jul 2, 2015 at 6:55 jackhammer013jackhammer013 2,29711 gold badges48 silver badges97 bronze badges4 Answers
Reset to default 19Note 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);
}
Also you should be aware of .call method which throws input context to function.
<input type='checkbox' checked='' onclick='changeEnable.call(this);' id='someid'>
function changeEnable()
{
var val = this.id;
alert(val);
}
use in this way:
<input type='checkbox' checked='' onclick='changeEnable(this);' id='someid'>
function changeEnable(el)
{
var val = el.id;
alert(val);
}