I am trying to get Attribute of input of type checbox but it keeps getting this error: "Uncaught TypeError: a.getAttribute is not a function"
$("#submit").click(function(){
var fields = document.getElementsByClassName("checkBox");
for(a in fields){
var x = a.getAttribute("id");
console.log(x);
}
please help, Thanks in advance
Here a
will be an integer, as a
is the index specifically, because for...in
iterates through object keys, and the indices are the array object keys AndrewLI :
for (a in fields){
var x = fields[a].getAttribute("id");
Or the better way to do is:
for (var a = 0; a < fields.length; a++)
var x = fields[a].getAttribute("id");
If you are using jQuery, as you have tagged it, please use:
$(".checkBox").each(function () {
var x = this.id;
console.log(x);
});
It is worth mentioning that it's important to prevent the default action:
$("#submit").click(function(e) {
e.preventDefault();
With all the above said, your final code should be:
$("#submit").click(function(){
$(".checkBox").each(function () {
var x = this.id;
console.log(x);
});
}); // missing );
Please note the missing braces.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.