I am trying to get the value from a checkbox using javascript.
I want only one checkbox value to be passed to the javascript function, and if multiple are selected, an alert box informing that only one box can be checked for the function.
I’ve tried this:
var publish_trigger = document.querySelector("#publish_trigger");
publish_trigger.onclick = function() {
var _posts = document.getElementsByName('post_id[]');
var check = _posts.checked;
var boxes = _posts.length;
var txt = "";
if(check.length > 1) {
alert("Only one at a time");
} else {
for (i = 0; i < boxes; i++) {
if (_posts[i].checked) {
txt = txt + _posts[i].value + " "
}
}
}
alert(txt);
return false;
}
This code is wrong:
getElementsByName()returns a NodeList (effectively an array) of elements, so your variable_postsdoesn’t have acheckedproperty. You need to loop through_poststo count the checked property on the individual elements within_posts.You already have a for loop so add the validation in there:
(Note: unrelated to your question, you should declare the loop counter
iwithin your function otherwise it will be global and might lead to hard to debug problems if you are using it in other places too.)