最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get id of an element through a function - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 19

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);
}

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);
}
发布评论

评论列表(0)

  1. 暂无评论