jQuery onClick capture the id of the element
i have many input fields like this
<i开发者_开发技巧nput 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
HTML:
<input type="radio" name="name" id="name" onchange="enableTxt(this)" />
JS:
function enableTxt(elem) {
var id = $(elem).attr("id");
alert(id);
}
The html
<button class="destroy" id="123">
The jQuery
$('button.destroy').on('click', function(e){
e.preventDefault();
console.log(this.id);
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);
}
pass this to the function
enableTxt(this)
function enableTxt(item) {
var id = $(item).attr("id");
alert(id);
}
Try this
alert($("input:radio").attr('id'));
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
Another option is with JQ
$("#name").on('onchange',enableText);
With this your object will be the current this
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>
精彩评论