admin管理员组文章数量:1415476
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');
...
});
本文标签: get checkbox name from javascriptStack Overflow
版权声明:本文标题:get checkbox name from javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745155530a2645149.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论