James Stafford
James Stafford

Reputation: 1054

textbox content resets immediately after changing

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?

Upvotes: 0

Views: 154

Answers (2)

Anoop
Anoop

Reputation: 23208

Form is getting submitted when you click on the buttons. use preventDefault to prevent this.

<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>

Upvotes: 1

Andreas
Andreas

Reputation: 21911

Add type="button" to your buttons

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

The default behaviour of a button without a type attribute is to submit the form it is part of. If you change the type to button it won't do anything :)

Upvotes: 3

Related Questions