Get the value of checked checkbox?

Viewed 1096924

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.

13 Answers
<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 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):

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

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 */

pure javascript and modern browsers

// for boolean
document.querySelector(`#isDebugMode`).checked

// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize

Example

<form>
  <input type="checkbox" id="isDebugMode"><br>
  <input type="checkbox" value="3" id="size"><br>
  <input type="submit">
</form>

<script>
  document.querySelector(`form`).onsubmit = () => {
    const isDebugMode = document.querySelector(`#isDebugMode`).checked
    const defaultSize = "10"
    const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
    //  for defaultSize is undefined or null
    // const size = document.querySelector(`#size:checked`)?.value
    console.log({isDebugMode, size})
    return false
  }
</script>

Related