Reputation:
I am writing a javascript program which is supposed to change the text of a textfield once submit button is clicked
<script>
function change()
{
document.getElementById("set").value="helloworld";
}
</script>
the textfield and submit button:
<form>
Enter Text <input type="text" id="set" >
<input type="submit" value="Press here" onclick="change()" />
</form>
once I press submit it only displays an empty textfield. But when I remove 'form' it displays the correct result. Can anyone explain why ?
On a similar note can anyone explain why 'form' is important when we can collect data without it as well..
Thanks in advance...
Upvotes: 0
Views: 73
Reputation: 36609
On click of the submit
button, form is being submitted and hence page is unloaded.
Prevent form submission.
function change(e) {
e.preventDefault();
//^^^^^^^^^^^^^^^^^^
document.getElementById("set").value = "helloworld";
}
<form>
Enter Text <input type="text" id="set">
<input type="submit" value="Press here" onclick="change(event)" />
</form>
Upvotes: 3