-2

I have these checkboxes:

<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
<input type="checkbox" class="ids" name="ids[]" value="5">
<input type="checkbox" class="ids" name="ids[]" value="6">

My question is via jquery, how would I loop through the ids[] on form submit?

$("#form").submit(function(e) {
  //Loop throught ids[] 
});

I have tried this:

$('input[type=checkbox][name=ids[]]').each(function () {   
  console.log("Here");
});

But it didn't work

11
  • What have you tried? What did work? And what did not? Commented Nov 9, 2018 at 19:42
  • Simple to target them by their class and loop over that collection using jQuery each. What exactly are you wanting to accomplish? Commented Nov 9, 2018 at 19:43
  • 1
    api.jquery.com/each i feel like this question could have been answered with a simple google search. Commented Nov 9, 2018 at 19:45
  • I am looking for get each of the checked values in an array to loop through it Commented Nov 9, 2018 at 19:45
  • 1
    [name=ids[]] is an invalid selector. put double quotes around the ids[] to force it to be a literal. But you don't have to do that. Just select using your class. Commented Nov 9, 2018 at 19:52

1 Answer 1

2

Your selector is invalid. You should escape [] with \\.

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. documentation

$('input[type=checkbox][name=ids\\[\\]]').each(function(){
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
<input type="checkbox" class="ids" name="ids[]" value="5">
<input type="checkbox" class="ids" name="ids[]" value="6">

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.