需要帮助将表单数据存储在数组中。
该表单具有显示其他字段的选项。如何获取要在数据数组中显示的附加字段值。
<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);
});
这是我的工作示例。
请注意,第一个字段值是在数据数组中设置的,但是当您添加其他字段时,它们不会。