我有一个数组:
var array = [
{id: "X", numberA: 1, numberB: 2, dif: 1},
{id: "Y", numberA: 2, numberB: 3, dif: 1},
{id: "Z", numberA: 3, numberB: 5, dif: 2},
]
我还有一个表格:
<form id="agenda_form">
<p>ID</p>
<input type="text" id="id">
<p>Start<p>
<input type="number" id="numberA">
<p>End</p>
<input type="number" id="numberB">
<input type="submit" value="Submit" id="submitForm">
</form>
我正在尝试使用该表单创建一个对象并将该对象推送到我的数组中。我可以通过从数字A中减去numberB来计算。
我尝试过使用jQuery和.val()但似乎无法弄明白。我该怎么做?
谢谢!
答案 0 :(得分:3)
这样的事情怎么样?
var array = [
{id: "X", numberA: 1, numberB: 2, dif: 1},
{id: "Y", numberA: 2, numberB: 3, dif: 1},
{id: "Z", numberA: 3, numberB: 5, dif: 2},
]
$("#agenda_form").on("submit", function(e) {
var numA = $("#numberA").val(),
numB = $("#numberB").val();
var obj = {
id: "", //whatever you need,
numberA: numA,
numberB: numB,
dif: numB - numA
};
array.push(obj);
//Prevent page from submitting
return false;
});
答案 1 :(得分:0)
试试这个。把它放到你的页面里。
HTML CODE
<form id="agenda_form">
<p>ID</p>
<input type="text" id="id">
<p>Start<p>
<input type="number" id="numberA">
<p>End</p>
<input type="number" id="numberB">
<input type="button" value="Submit" id="submitForm">
</form>
JS CODE
$(document).ready(function() {
var array = [
{id: "X", numberA: 1, numberB: 2, dif: 1},
{id: "Y", numberA: 2, numberB: 3, dif: 1},
{id: "Z", numberA: 3, numberB: 5, dif: 2},
];
$('#submitForm').on('click', function(){
var id = $('#id'),
numberA = $('#numberA'),
numberB = $('#numberB');
var k = {id:'', numberA: '', numberB: '', dif: ''};
k.id = id.val();
k.numberA = numberA.val();
k.numberB = numberB.val();
k.dif = parseInt(k.numberB) - parseInt(k.numberA);
array.push(k);
});
});