Harsha M V
Harsha M V

Reputation: 54989

jQuery onClick capture the id of the element

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

Upvotes: 38

Views: 118957

Answers (8)

Jordy
Jordy

Reputation: 1967

You can use jQuery onclick method be like :

$('input[type="radio"]').click((e)=> {
  id = e.target.id;
  console.log('id = ',id);
});
<input type="radio" name="name" id="name" />
<label for="name">Click Me</label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

MandraSaptak Mandal
MandraSaptak Mandal

Reputation: 11

This video might be helpful:- https://youtu.be/gO286Isc5FM

I was trying with $(this).attr(id)

But was returning an undefined error

But using this method(in the video) worked

My use case: <h1 id = "Autogenerated" Onclick="print(this)">AutoGeneratedlistItems<h1>"

function print(listItem){console.log(listItem.id) } which outputs the id of the Clicked element

Upvotes: 1

Harry Bosh
Harry Bosh

Reputation: 3800

The html

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

The jQuery

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

Upvotes: 10

Felipez
Felipez

Reputation: 468

Another option is with JQ

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

With this your object will be the current this

Upvotes: 0

Michael Low
Michael Low

Reputation: 24506

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

Upvotes: 5

Rahul Chordiya
Rahul Chordiya

Reputation: 542

Try this

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

Upvotes: 2

kobe
kobe

Reputation: 15835

pass this to the function

enableTxt(this)

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

Upvotes: 2

Calvin
Calvin

Reputation: 8775

HTML:

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

JS:

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

Upvotes: 70

Related Questions