0

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.

0

1 Answer 1

1

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:

  1. (Simplest) Remove the form tag - it is not used to submit anything so removing it should leave things still working

  2. 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">

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Mahout , I just removed the form tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.