问题描述:

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:

var resp = [ ];
$("input[id^= 'Answer_Response']").each(function() {
    // Pull the number out of things like "Answer.Response[2]"
    var i   = parseInt(this.id.match(/\d+/)[0], 10);
    resp[i] = this.checked;
});

That should get the job done as long as the id attributes 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 your id attributes (or you'll get some undefined entries in your resp array).

And a simple demo: http://jsfiddle.net/ambiguous/hHS2K/

相关阅读:
Top