我正在尝试获取用户输入(债务),保存到本地存储,并将用户输入显示到div(结果)以获取结果。当我点击提交按钮时,什么也没有发生。我想做的是将债务输入推送到数组,然后将其发布到结果div。
HTML:
<form id="myForm">
这是输入开始的地方,有3种不同的类型;名称,金额和应付款
<!-- entering debt name -->
<div class="name" id="name">
<label>Debt Name: </label>
<input type="text" class="debtname" id="debtname">
</div>
<!-- entering debt amount -->
<div class="amount" id="amount">
<label>Amount: </label>
<input type="number" class="debtamount" id="debtamount">
</div>
<!-- entering debt due date -->
<div class="due" id="due">
<label>Due Date: </label>
<input type="number" class="debtdue" id="debtdue" min="1" max="31">
</div>
<!-- sumbitting debt information -->
<input type="button" class="submitdebt" id="submitdebt" onclick="insert()" value="Submit"/>
</form>
这是我希望发布结果的div
<!-- input results -->
<div class="results" id="results"></div>
</div>
</div>
JavaScript:
document.getElementById('myForm').addEventListener('submit', saveDebt);
// Save Debt
function saveDebt(e) {
// Get form values
var debtName = document.getElementById('debtname').value;
var debtAmount = document.getElementById('debtamount').value;
var debtDue = document.getElementById('debtdue').value;
if(!validateForm(debtName, debtAmount, debtDue)) {
return false;
}
我希望所有输入都作为对象传递到数组中
var debtObject = {
name: debtName,
amount: debtAmount,
due: debtDue
}
我认为这是主要问题,我认为输入没有被推入数组
// Test if debts is null
if(localStorage.getItem('debts') === null) {
// Init array
var debts = [];
// Add to array
debts.push(debtObject);
// Set to localStorage
localStorage.setItem('debts', JSON.stringify(debts));
} else {
// Get debts from localStorage
var debts = JSON.parse(localStorage.getItem('debts'));
// Add debt to array
debts.push(debtObject);
// Re-set back to localStorage
localStorage.setItem('debts', JSON.stringify(debts));
}
// Clear form
document.getElementById('myForm').reset();
// Re-fetch debts
fetchDebts();
// Prevent form from submitting
e.preventDefault();
}
此功能可将结果打印到结果div
// Fetch debts
function fetchDebts() {
// Get debts from localStorage
var debts = JSON.parse(localStorage.getItem('debts'));
// Get output id
var results = document.getElementById('results');
// Build output
results.innerHTML = '';
for( var i = 0; i < debts.length; i++) {
var name = debts[i].name;
var amount = debts[i].amount;
var due = debts[i].due;
results.innerHTML += '<div class="well">'+
'<p>' + 'Name: ' + name +
'Amount: ' + amount +
'Due: ' + due +
'</h3>'+
'</div>';
}
}
// Validate Form
function validateForm(debtName, debtAmount, debtDue) {
if(!debtName || !debtAmount || !debtDue) {
alert('Please fill in the form');
return false;
}
return true;
}
// modal end
答案 0 :(得分:0)
我创建了一个jsfiddle,以使其在此处调试代码更容易(并对其进行了修复)-http://jsfiddle.net/9ra0dhtg/6/
我在您的代码中发现您有:
<input type="button" class="submitdebt" id="submitdebt" onclick="insert()" value="Submit"/>
我假设您可能想在这里致电saveDebt
。如果不是,则由于您正在尝试处理表单提交事件,因此应仅将其创建为表单提交输入(type="submit"
)并删除onclick处理程序,其余流程将按您的预期进行。