jQuery onClick capture the id of the element

2020-02-27 01:36发布

问题:

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

回答1:

HTML:

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

JS:

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


回答2:

The html

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

The jQuery

  $('button.destroy').on('click', function(e){
    e.preventDefault();
    console.log(this.id);


回答3:

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


回答4:

pass this to the function

enableTxt(this)

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


回答5:

Try this

alert($("input:radio").attr('id'));


回答6:

Another option is with JQ

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

With this your object will be the current this