Need help storing form data in an array.
The form has an option to display additional fields. How do I get the additional field values to display in the data array.
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<p>Please Enter Your First Name Last Name</p>
<div style="border:1px solid black;padding:5px">
<label for="first1">first:</label>
<input type="text" name="first1" id="first1" /><br />
<label for="last1">last:</label>
<input type="text" name="last1" id="last1" /><br />
</div>
<p>Please Enter Your Address</p>
<div style="border:1px solid black;padding:5px">
<label for="add1">address:</label>
<input type="text" name="add1" id="add1" /><br />
<select class="period" id="hour1" name="hour1">
<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>
<option value="11">11</option>
<option value="12" selected>12</option>
</select>
</div>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
</div>
<div style="padding-top:30px">
<input type="button" id="submit" value="submit to Object" />
</div>
</form>
var storeData = {
"firstname": "",
"lastname": "",
"address": "",
"hour": ""
};
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
});
$('#submit').click(function() {
var firstname = $('#first1').val();
var lastname = $('#last1').val();
var address = $('#add1').val();
var hour = $('#hour1').val();
storeData.firstname = firstname;
storeData.lastname = lastname;
storeData.address = address;
storeData.hour = hour;
console.log(storeData);
});
Here is my working example.
http://jsfiddle.net/FFueC/8/
Note the first fields values are set in the data array but when you add additional fields they are not.
You can use .serializeArray() which will create an object with all form inputs:
$('#submit').click(function() {
var data = $('#myForm').serializeArray();
for(i in data){
console.log(data[i]);
}
});
jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With