views:

39

answers:

1

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 need to iterate and manually construct the string? (if if manually...how's that look?)

thx

+5  A: 

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.

Nick Craver
+1 48 seconds faster ;) A class could also be added to the elements...
Felix Kling
@Felix - Agreed, or if we had a bit more context, they're probably all in a single container given how they're being generated.
Nick Craver
Indeed - i pulled the 'class=emailInput' from the OP for sake of brevity. How would that change the answer? - very much appreciated!
justSteve
@justSteve - Just use `$(".emailInput")` for your selector :)
Nick Craver