Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of checked checkbox?

So I've got code that looks like this:

<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">

I just need Javascript to get the value of whatever checkbox is currently checked.

EDIT: To add, there will only be ONE checked box.

like image 522
Matthew 'mandatory' Bryant Avatar asked Sep 29 '22 17:09

Matthew 'mandatory' Bryant


2 Answers

None of the above worked for me but simply use this:

document.querySelector('.messageCheckbox').checked;
like image 329
JanBorup Avatar answered Oct 08 '22 17:10

JanBorup


For modern browsers:

var checkedValue = document.querySelector('.messageCheckbox:checked').value;

By using jQuery:

var checkedValue = $('.messageCheckbox:checked').val();

Pure javascript without jQuery:

var checkedValue = null; 
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           checkedValue = inputElements[i].value;
           break;
      }
}
like image 313
Engineer Avatar answered Oct 08 '22 18:10

Engineer