I have the following code in jQuery that returns an array called responses. The array returned is based on the
position of the input elements.
var resp = $("input[id^= 'Answer_Response']");
responses: jQuery.map(resp, function (a) { return a.checked; })
<input id="Answer_Response[2]" name="Answer.Response[2]" type="checkbox" />
<input id="Answer_Response[0]" name="Answer.Response[0]" type="checkbox" />
<input id="Answer_Response[1]" name="Answer.Response[1]" type="checkbox" />
<input id="Answer_Response[4]" name="Answer.Response[4]" type="checkbox" />
<input id="Answer_Response[3]" name="Answer.Response[3]" type="checkbox" />
so When the inputs are:
false // for Answer.Response[2]
true // for Answer.Response[0]
true // for Answer.Response[1]
false // for Answer.Response[4]
true // for Answer.Response[3]
the responses array looks like false, true, true, false, true
what I need is for the array returned to be based on the id number for the elements. So for example I need an
array returned that looks like this: true, true, false, true, false
true // for Answer.Response[0]
true // for Answer.Response[1]
false // for Answer.Response[2]
true // for Answer.Response[3]
false // for Answer.Response[4]
Is there some way that I can do this in jQuery? please note that I can’t change the way that the responses are displayed. I’ve been asked to do this all in jQuery.
I hope someone can give some advice. I guess I just need some different way to do the mapping of resp but I’m not sure how I can do it.
One way would be to use
each:That should get the job done as long as the
idattributes have exactly one substring that looks like a number (or at least the first match is the one you want) and there aren’t any gaps in youridattributes (or you’ll get some undefined entries in yourresparray).And a simple demo: http://jsfiddle.net/ambiguous/hHS2K/