Reputation: 1120
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 [""]
Upvotes: 1
Views: 326
Reputation: 148120
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();
Upvotes: 3
Reputation: 20636
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();
Upvotes: 2