Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

thx

like image 397
justSteve Avatar asked Sep 02 '10 18:09

justSteve


1 Answers

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.

like image 72
Nick Craver Avatar answered Nov 10 '22 14:11

Nick Craver