[javascript] 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.

This question is related to javascript checkbox

The answer is


This does not directly answer the question, but may help future visitors.


If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.

This can be done in the HTML:

<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>

or with JavaScript:

cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})

If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.

  $(document).on("change", ".messageCheckbox", function(evnt){
    var data = $(".messageCheckbox");
    data.each(function(){
      console.log(this.defaultValue, this.checked);
      // Do something... 
    });
  }); /* END LISTENER messageCheckbox */

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    _x000D_
    if (ckbox.is(':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
    });_x000D_
       _x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
_x000D_
_x000D_


If you're using Semantic UI React, data is passed as the second parameter to the onChange event.

You can therefore access the checked property as follows:

<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />

in plain javascript:

function test() {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
    }
}
function selectOnlyOne(current_clicked) {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        cboxes[i].checked = (cboxes[i] == current);
    }
}

I am using this in my code.Try this

var x=$("#checkbox").is(":checked");

If the checkbox is checked x will be true otherwise it will be false.


Use this:

alert($(".messageCheckbox").is(":checked").val())

This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.


In my project, I usually use this snippets:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.


None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):

_x000D_
_x000D_
function checkbox() {_x000D_
  var checked = false;_x000D_
  if (document.querySelector('#opt1:checked')) {_x000D_
     checked = true;_x000D_
  }_x000D_
  document.getElementById('msg').innerText = checked;_x000D_
}
_x000D_
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
_x000D_
_x000D_
_x000D_


<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
    alert(value);
}

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

document.querySelector('.messageCheckbox').checked;

Happy coding.