I am trying to get a checkbox name when a checkbox is clicked...i am using a javascript function but it returns undefined.
Here is the code:
notType= document.getElementById($('[type="checkbox"]').attr('id')).value;
alert(notType);
I am trying to get a checkbox name when a checkbox is clicked...i am using a javascript function but it returns undefined.
Here is the code:
notType= document.getElementById($('[type="checkbox"]').attr('id')).value;
alert(notType);
Share
Improve this question
edited Dec 4, 2023 at 12:47
BalusC
1.1m376 gold badges3.7k silver badges3.6k bronze badges
asked Nov 20, 2015 at 13:59
user3576758user3576758
291 gold badge1 silver badge4 bronze badges
2
- 2 Why would you select an element with jQuery than use getElementById? Now you want the name and you are reading the value? – epascarello Commented Nov 20, 2015 at 14:01
- Does this answer your question? How can I get checkbox attribute with using javascript? – Shiladitya Commented Dec 4, 2023 at 12:51
5 Answers
Reset to default 1In your code example, you are retrieving the value of the field, rather than the name. Instead, you should use:
var notType = document.getElementById(id).name;
This should work. $("#" + id)
finds the element with the specified id. After that, you get the attribute called "name".
var notType = $("#" + id).attr("name");
you can do it like this:
$('input[type="checkbox"]').on('click', function(event){
alert(event.target.id);
});
let checkbox = $("input[type="checkbox"]");
// if (checkbox.is(":checked")) { OR
if (checkbox.prop('checked') == true){
let name = checkbox.name;
}
Pure JavaScript way of getting the checkbox name attribute when clicked:
document.querySelector('input[type="checkbox"]').addEventListener('click', ({ target }) => {
const name = target.getAttribute('name');
...
});
JQuery way of getting the checkbox name attribute when clicked:
$('input[type="checkbox"]').on('click', function() {
const $checkbox = $(this);
const name = $checkbox.attr('name');
...
});