开发者

jQuery - Easiest way to pull multiple .(val) into one string

Given an unknown number of dynamically produced text inputs:

for (var i = 0; i < numInputs2Render; i++) {
    collectEmails = collectEmails + '<input type="text" id="Email' + i + '" name="Email' + i + '">';
}

I need to produce a comma delimited string of the combined input values. Does jQuery give me a one-step solution or will i ne开发者_运维问答ed to iterate and manually construct the string? (if if manually...how's that look?)

thx


You can use .map(), like this:

var emails = $("input[name^=Email]").map(function() { return this.value; })
                                   .get().join(',');

This uses the attribute-starts-with selector to find the inputs, then .map() to get the values into an array you can .join() into a single string.

If they're in a container, say a <div id="Emails"> you could slim the selector down to something like $("#Emails input"), I can't say for sure without seeing your markup, but anything with a container selector will make it more efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜