0

I have built a basic script to do an elementary math add 1 on click and subtract 1 on click the problem is every time you click on the button you can watch the textbox content increase by 1 or decrease by 1 but then within a quarter of a second the form appears to reset and show the initial value of 0 again

<html>
<head>
<script>
function inc()
{
document.content.quant.value++;
}

function dec()
{
document.content.quant.value--;
}
</script>
</head>

<body>
<form name="content">
<input type="text" id="quant" value="0">
<button onclick="inc()">increase</button>
<button onclick="dec()">decrease</button>
</form>
</body>
</html>

I am sure I am making some stupid mistake - any ideas?

4

2 回答 2

3

添加type="button"到您的按钮

<button type="button" onclick="inc()">increase</button>

没有属性的按钮的默认行为type是提交它所属的表单。如果你改变它typebutton它不会做任何事情:)

于 2012-09-18T20:07:36.997 回答
1

当您单击按钮时,表单正在提交。使用 preventDefault 来防止这种情况。

<html>
<head>
<script>
function inc()
{
document.content.quant.value++;
event.preventDefault();
}

function dec()
{
document.content.quant.value--;
event.preventDefault();
}
</script>
</head>

<body>
<form name="content">
<input type="text" id="quant" value="0">
<button onclick="inc()">increase</button>
<button onclick="dec()">decrease</button>
</form>
</body>
</html>
于 2012-09-18T20:13:13.583 回答