Although I am able to call Javascript function on hitting the enter key. I am calling a function shortIt()
when user hits the enter key, shortIt()
takes the text from input box and makes a request to Google URL Shortener API which returns a short URL, but the generated response is visible for only some seconds. I am showing the response in a div.
Seems to be very weird problem, code is here https://s3-ap-southeast-1.amazonaws.com/s3freebucket/URLShortner/url-shortner.html
But when I click on shortIt
button to short the url. It works fine and the response text stays in the div.
This is because on pressing the enter key, the form
gets submitted. When this happens you will notice the page reloading. This is a default behaviour and is the consequence of using <form>
. On form submission, the page in the forms action
attribute is loaded. In this case the action
attribute of the <form>
is not set and so the page you are on is just reloaded, thus the script stops running and the page reloads.
Two straight forward options for fixing this:
(Simplest) Remove the form tag - it is not used to submit anything so removing it should leave things still working
Prevent the default action when the form submit
event is fired.
With JQuery:
$('#myForm').on('submit', function (evt) { evt.preventDefault(); // prevents form submission });
Where myForm
is the ID of your form tag. You will need add an id attribute to your existing html form tag: <form id="myForm" class="form-horizontal">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.