SoFunction
Updated on 2025-04-14

JavaScript Basic Tutorial (Lesson 5) Page 3/4

Forms are also objects; they have their own methods, properties and event handlers. One of them is onSubmit.

There are two situations for calling onSubmit: if the user clicks the Submit button, or the user presses the Enter key in the text field, onSubmit will be triggered.

In Netscape, clicking a Submit button with no result event processing will usually cause the original page to be refreshed. To avoid this, you can do this:

    <form onSubmit="return false;">
        <input type="submit" value="Submit">
    </form>

Javascript uses return false to prevent browsers from refreshing pages. Another example is to prevent a href from turning to an URL that assigns. For example: link

    <a href="" onClick="return false;">sohu!</a>

No URL is turned to, because you assign the value to onClick as return false.

The following is a form to obtain information from users. Enter something in the text field and press Enter:

    Who does the monkey love:

   

The following is the encoding of the form:

    <form name="text_entry_form" onSubmit="monkeyLove(); return false;">
        <input type="text" name="monkey_love" size="40">
    </form>

When you click Enter in the text field, the onSubmit processor is called to execute the function monkeyLove(), which will change the value in the text field.

If there is no return false statement in the onsubmit processor, executing the function monkeyLove() will change the text domain content, but since the web page content will be refreshed at the same time, the content of the text domain will be returned to the original content. To prevent this, return false must be added to onSubmit.

The following is the content of the monkeyLove() function:

    function monkeyLove()
    {
        var who_it_is = .text_entry_form.monkey_love.value;

        who_it_is = 'The monkey loves ' + who_it_is;
        .text_entry_form.monkey_love.value = who_it_is;
    }

Previous page1234Next pageRead the full text