Reputation: 19
I think that I understand that "button" are supposedly the correct way to achieve the result I desire; somehow they are supposed to be different from submit buttons. But I don't understand how to get the result I want.
I have the following:
<form action="http://www.google.com">
<input type="text" id="box1">
<button id="button1" onclick="myFunction()">Submit</button>
</form>
If a user clicks the button, the function runs correctly. (The function ultimately pulls the value from box1) and does something with it). However, if while the user has their cursor inside the textbox, they hit enter on their keyboard, the form submits and links to google.
How can I make it so that hitting enter in box1 does not change the page, and instead runs myFunction?
Upvotes: 0
Views: 83
Reputation: 318352
Add proper event handlers and listen for the submit event instead
<form action="http://www.google.com" id="myForm">
<input type="text" id="box1">
<button id="button1">Submit</button>
</form>
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
myFunction()
}, false);
</script>
Upvotes: 2