0

I want to get values into an array (checkslist) from checked checkboxes. I tried this code but it does not seems to work. In the for I can get "checkslist"s items which is push but after for it can't. How can I get all the checked CheckBoxes's values into an array or list?

$(function() {
  $("#btnEkle").click(
    function() {
      var checkbox, checkslist, menuId, text, vModel;
      checkslist = [];
      checkbox = document.getElementsByClassName("checks");

      for (var i = 0; checkbox.length; ++i) {
        if (checkbox[i].checked) {
          menuId = checkbox[i].value;
          checkslist.push(menuId);
        }
      }      
      alert(checkslist[0].value)
    })    
})

3 Answers 3

1

Problem is with your for loop,

for (var i = 0; checkbox.length; ++i) {

You should iterate your loop like this,

for (var i = 0; i<checkbox.length-1; i++) {
    if (checkbox[i].checked) {
         menuId = checkbox[i].value;
         checkslist.push(menuId);
    }
}

And your alert should be,

alert(checkslist[0] )

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

You can loop all checkboxes and add them to the array like this list.push(($(this).prop("checked"))); checked returns either true or false if the box is checked

function getList() {
  var list = []
  $.each($("input:checkbox"), function() {
    list.push(($(this).prop("checked")));    
  });
  console.log(list)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

<button onClick="getList()">Get list</button>

Comments

0

If you want all the checked values to appear in your alert you should combine them into a string. This function gets all checkboxes with the class "checks" as in your example function, adds those values that are checked to an array and creates a string for the alert that contains all checked values. The array of values is returned, in case you want to use that somewhere else.

function getChecked(){
    let checks = document.getElementsByClassName("checks");
    let checked_values = [];
    let checked_values_string = "";
    for(let i=0; i<checks.length; i++){
        if(checks[i].checked){
            checked_values.push(checks[i].value);
            checked_values_string = checked_values_string + checks[i].value + " ";
        }
    }
    alert(checked_values_string);
    return checked_values;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.