266

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.

Richard Barker
  • 1,161
  • 2
  • 12
  • 30

16 Answers16

353

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

document.querySelector('.messageCheckbox').checked;
Nimantha
  • 6,405
  • 6
  • 28
  • 69
JanBorup
  • 5,337
  • 1
  • 29
  • 17
  • I concur. You confirmed what I thought. I like to put var chk1= document.getElementById('messageCheckbox'); That way I can reference the "chk1" variable's properties: checked, enabled, style, etc. – JustJohn Mar 24 '16 at 21:26
  • 4
    Where did you get that `id`? Can you please explain? The guy who asked the question used `class` in the input actually. It will be good if you can provide the full code so I can understand from where you got the `id` – devfaysal Apr 26 '16 at 02:41
  • 5
    This can't work with the example code provided by OP... I'm curious why it got so many upvotes while not answering the question, although a quick fix might make it right. – Laurent S. May 15 '16 at 16:24
  • 1
    Can you edit your proposed answer to expand on what this does and how it addresses the OP? – Ro Yo Mi May 15 '16 at 21:07
  • 2
    surprised how this answer got many votes!! it is bad practice to use same id for multiple times in a page – Pradeep Kumar Dec 08 '16 at 10:22
  • 3
    @PradeepKumarPrabaharan probably people like me (not using id for multiple items) wondering why .value was giving them undefinied. –  Mar 09 '17 at 18:31
330

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;
      }
}
Engineer
  • 47,849
  • 12
  • 88
  • 91
  • 10
    @Mageek it's bad practice to add same id on multiple elements. – Engineer Jul 22 '12 at 11:11
  • @Engineer No, just putting a different id for each checkbox. – Alexandre Khoury Jul 22 '12 at 11:14
  • @Mageek There will be no benefits. – Engineer Jul 22 '12 at 11:18
  • 3
    @Engineer "Saving bytes" because we must simply write `document.getElementById("foo").value();` and "saving calculations" because `getElementById` is surely speedier than `getElementsByTagName` and a loop. – Alexandre Khoury Jul 22 '12 at 11:20
  • @Mageek Yes, `document.getElementById` is faster, but you should perform as much `document.getElementById` calls,as there are checkboxes, and *which even worse*, you **have to hardcode all the ids in your script**. – Engineer Jul 22 '12 at 11:22
  • 13
    for jQuery `.is(":checked")` is the correct way as `.val()` will return the attribute value if its defined.. and even if its not defined it will return "on" and not a boolean value.. http://jsfiddle.net/d5f7wnzu/ – Peter Mar 13 '15 at 12:02
  • I think what @Mageek is saying is that if you have a huge page (imagine a huge table with 100000000 rows and columns :) inside), the selector ".messageCheckbox:checked" may loop inside every cell of it to search for checkboxes, even if there is none anywhere (at least on older browsers it sure did). Using ids is usually faster, so you may put a single div with an id like "#checkboxesarehere" around them and use document.querySelector('#checkboxesarehere .messageCheckbox:checked') to limit the search to that area of the document. Of course here is just an example so I'd leave it as it is. – FrancescoMM Jul 24 '15 at 09:36
  • @FrancescoMM If you have millions of input cells, then your UI sucks. There is no need to show millions of input boxes, that the client will fill on his/her entire life. It would be better to think about the changing the UI ;) – Engineer Jul 24 '15 at 10:48
  • @Engineer agreed indeed, but who talked about a million of input boxes? A .messageCheckbox selector will search in every div, in every td, in every dom node of any kind... Even if you have only one checkbox. – FrancescoMM Jul 25 '15 at 12:44
  • 3
    `document.querySelector('.messageCheckbox:checked').value` generates TypeError if no checkbox is checked – Meisner Nov 29 '16 at 13:44
  • 1
    This blows up - Uncaught TypeError: Cannot read property 'value' of null – Mr Nellinger Apr 02 '20 at 17:52
  • 1
    Might want to add that in the vanilla JS case `.checked` returns a `boolean`, `true`/`false`. – rustyx Oct 10 '20 at 20:03
  • This code work for me: var items = []; var checkedValue = document.querySelectorAll('.checkbox:checked'); for (var i = 0; i < checkedValue.length; i++) { items.push(checkedValue[i].value); } alert(items); – Duc Manh Nguyen Jul 30 '21 at 04:44
140

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.

user1683014
  • 1,681
  • 1
  • 11
  • 6
25

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);
    }
}
Stano
  • 8,749
  • 6
  • 30
  • 44
13

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})
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
7

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

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.

jackJoe
  • 11,078
  • 8
  • 49
  • 64
4
<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);
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Alien
  • 121
  • 1
  • 1
  • 11
3

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>
spice
  • 1,442
  • 19
  • 35
1

if you using after an event occurred you can use

const selected = event.target.checked; //true or false

An example would be if you want to track selected items, here is an example using react react-hook-form react material ui, it would be better than using value from rendered field that give wrong values

...
const [selectedQuestions, setSelectedQuestions] = useState(0);

const handleSelectedQuestions = (checked) => {
  if (checked) {
    setSelectedQuestions((prev) => prev + 1);
  } else {
    setSelectedQuestions((prev) => prev - 1);
  }
};

<Controller
  key={item.id}
  control={control}
  name={`question-${item.id}`}
  defaultValue={false}
  render={({ field: { onChange } }) => (
    <Grid key={item.id} item xs={12}>
      <QuestionCard
        item={item}
        handleOpen={handleOpen}
        isLoading={isLoading}
        isError={isError}
        onChange={(event) => {
          handleSelectedQuestions(event.target.checked);
          onChange(event);
        }}
      />
    </Grid>
  )}
/>
...
export default function QuestionsCard({ item, handleOpen, onChange }) {
  return (    
    ...
    <FormControlLabel
      control={
        <Checkbox
          // checked={value}
          onChange={onChange}
          sx={{
            '& svg': {
              fontSize: '1.266rem',
            },
          }}
        />
      }
    />
  )
}
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
  • @herrstrietzel, it was about javascript the first line answer the question then the second code is how to use the first code in react and I have mentioned this too react, react hook form, react material ui – DINA TAKLIT Mar 04 '23 at 01:08
0

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)} />
Dave Clark
  • 2,243
  • 15
  • 32
0

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 */
Dharman
  • 30,962
  • 25
  • 85
  • 135
DanimalReks
  • 315
  • 4
  • 12
0

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>
Carson
  • 6,105
  • 2
  • 37
  • 45
0

Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:

Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) { 
      return v.value; 
  });
bomberjackets
  • 342
  • 3
  • 16
0

You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.

$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript

To obtain the value checked in jQuery:

$(".messageCheckbox").is(":checked").val();
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
-7

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
VanThaoNguyen
  • 792
  • 9
  • 20