Get the value of checked checkbox?

Matthew 'mandatory' Bryant picture Matthew 'mandatory' Bryant · Jul 22, 2012 · Viewed 845.4k times · Source

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.

Answer

Engineer picture Engineer · Jul 22, 2012

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;
      }
}