I have a page that creates a number of inputs based on the user's selection of how many to create:
select id="noOfDirectors" name="amount" onchange="addInput();">
<option value="">How Many Directors</option>
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
<option value="5" >5</option>
<option value="6" >6</option>
<option value="7" >7</option>
<option value="8" >8</option>
<option value="9" >9</option>
<option value="10" >10</option>
</select>
<div id="inputs"></div><br/>
<button id="nod" onclick="return false">Submit</button>
The .js file creates the forms:
function addInput(){
noOfDirectors = $('#noOfDirectors').val();
var inputs = $('#inputs').empty();
inputs.innerHTML = "";
for(i = 0; i < noOfDirectors; i++) {
inputs.append('Director '+ (i+1) +' Name: <input type="text" name="directorName[' + i + ']" /><br/>Director '+ (i+1) +' Customer Number: <input type="text" name="directorECN['+i+']" /><br/><br/>');
}
$("#nod").show();
directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
}
$(document).ready(function() {
$('#nod').click(function() {
console.log(directors);
});
});
Now, I want to take each of those directorECN['+i+'] input names and add them to a globally declared array:
var directors = new Array ();
I am having a hard time figuring out a syntax that works without hard coding 10 (0-9) of each of the possible input names. Is there an easier way to do this?
Here is my UPDATED JSFiddle
Updated my JS above. Console is printing [""]
-
You didn't explain why would you need that, but sounds like you just want to serialize the FORM, see: api.jquery.com/serialize or api.jquery.com/serializearrayA. Wolff– A. Wolff2015年05月20日 08:39:28 +00:00Commented May 20, 2015 at 8:39
-
later in the code, I need to list out at different times after I sort the inputs.jpgerb– jpgerb2015年05月20日 08:46:13 +00:00Commented May 20, 2015 at 8:46
2 Answers 2
You can use .map() to get the array from name attribute of elements returned by Attribute Starts With Selector [name^="value"].
var directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
13 Comments
.get() in the end. It will return pure JS array instead of jQuery collection object.var directors = new Array();. But again uses var directors inside the function. [] returned is for global variable.var from var directors = ...map() inside the function.Use .map() function over the attribute starts with selector [attribute^="value"]
var directors = $('[name^="directorECN"]').map(function () {
return this.name //to get value use this.value
}).get();
2 Comments
name array, which was edited later , Still I'd ask, should I remove mine?