jQuery onClick capture the id of the element

2020-02-27 02:03发布

i have many input fields like this

<input type="radio" name="name" id="name" onchange="enableTxt()" /> 

when i click this radio button i wanna capture the id of the radio input. i am using the following code

function enableTxt() {
    var id = $(this).attr("id");
    alert(id);
}

Am getting this error

a.attributes is undefined

6条回答
Viruses.
2楼-- · 2020-02-27 02:29

The html

 <button class="destroy" id="123">

The jQuery

  $('button.destroy').on('click', function(e){
    e.preventDefault();
    console.log(this.id);
查看更多
三岁会撩人
3楼-- · 2020-02-27 02:30

Another option is with JQ

$("#name").on('onchange',enableText);

With this your object will be the current this

查看更多
叛逆
4楼-- · 2020-02-27 02:32

Try this

alert($("input:radio").attr('id'));
查看更多
We Are One
5楼-- · 2020-02-27 02:36

pass this to the function

enableTxt(this)

function enableTxt(item) {
    var id = $(item).attr("id");
    alert(id);
}
查看更多
劳资没心,怎么记你
6楼-- · 2020-02-27 02:37

HTML:

<input type="radio" name="name" id="name" onchange="enableTxt(this)" /> 

JS:

function enableTxt(elem) {
    var id = $(elem).attr("id");
    alert(id);
}
查看更多
Ridiculous、
7楼-- · 2020-02-27 02:39

You can pass just the ID from the HTML

<input type="radio" name="name" id="name" onchange="enableTxt($(this).attr('id'))" />

function enableTxt(id)
{
    alert(id);
}
查看更多
登录 后发表回答