0

I have an array of input boxes like so.

<form>
  9 <input type="checkbox" name="date[]" value="9">
  10 <input type="checkbox" name="date[]" value="10">
  11 <input type="checkbox" name="date[]" value="11">
</form>

I need the values stored in the date array, to pass it to an ajax call.

I've tried

    console.log($("input[name^=date]").val());

But this only outputs 9. I could always check if the individual elements are checked and then get their values, make an array and pass it to the ajax call, but is there a way to do this directly?

EDIT : Why does the console.log($("input[name^=date]").val()); output 9 only?

1
  • 1
    First line from api.jquery.com/val : Get the current value of the first element in the set of matched elements. (emphasis mine) Commented Sep 16, 2014 at 16:27

3 Answers 3

2

You can do:

var values = $("input[name='date[]']:checked").map(function() {
    return this.value;
}).get();

values will be an array of the values of the checked boxes.

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

Comments

1

If you're submitting the data via ajax, you just need to serialize the form to get all the data, already URL-encoded:

 $('form').serialize();

For example, if all checkboxes are selected, you will get the following data:

date%5B%5D=9&date%5B%5D=10&date%5B%5D=11 
//which is date[]=9&date[]=10&date[]=11

And PHP can comfortably handle the array parameter: date[].

1 Comment

Awesome! I didn't know about .serialize(). jQuery continues to surprise me!
0

Try each

var arr = []
$("input[name^=date]").each(function(){
     arr.push($(this).val())

})

Fiddle

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.