2

I want to push { "studentid": achecked[index].value } this into a array, but if i push it my array is like this (2) [{…}, {…}] and not my checkbox value.

this is my code:

 var achecked = $("form input:checkbox:checked");
var values = [];
achecked.each(function (index) {
    var student = { "studentid": achecked[index].value };
    values.push(student);
});
console.log(values);

var postdata = {
    'displayname': $("#displayname").val(),
    'email': $("#email").val(),
    'students': [
    ]
};
postdata.students = values;
<input type="checkbox" name="toevoegen" value="10" />
<button class="btn btn-success" id="aanmaken">Aanmaken</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

does someone knows and could help me?

6
  • Have you tried clicking the {...} in your console log output? Commented Oct 11, 2018 at 11:30
  • @OKsure Yes it's empty, it show the same... Commented Oct 11, 2018 at 11:30
  • Would you add in the snippet some example of the checkboxes? Commented Oct 11, 2018 at 11:34
  • check achecked length Commented Oct 11, 2018 at 11:35
  • I think the issue may be that you have no form element but your selector is looking for one. Commented Oct 11, 2018 at 11:39

1 Answer 1

1

Seems to be working for me. Not sure what your HTML looks like, but the selector form input:checkbox:checked will require a form around all the checkboxes.

$('button').on('click', function(e) {
  e.preventDefault();
  var achecked = $("form input:checkbox:checked");
  var values = [];
  achecked.each(function (index) {
      var student = { "studentid": achecked[index].value };
      values.push(student);
  });
  console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" checked value="1" />
<input type="checkbox" checked value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" checked value="4" />
<input type="checkbox" checked value="5" />
<button>Submit</button>
</form>

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

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.