Dirty Penguin
Dirty Penguin

Reputation: 4402

Unable to get value of form field

I'm learning javascript and tried my hand at calling functions. Based on the example here, I tried to use the logic in my test html:

<html>
    <head>
        <script>
            function ShowForm()
            {
            var field_value = document.forms["test_form"]["my_name"].value;
            document.write(field_value);
            }
        </script>
    </head>
    <body>
        <form action="" name="test_form" onsubmit="return ShowForm();" method="post">
            <input type="text" name="my_name" placeholder="Type your name"/>
            <button type="submit">My button</button>
        </form>
    </body>
</html>

I found that the html renders correctly, however upon clicking the "My button" button, the page simply reloads without displaying the additional html I expected.

The main different is that I'm trying to use <button> for the click/submit action. Is it possible to use a <button> and activate the javascript? Or should I just style the <input> as a button?

What am I doing wrong here?

Upvotes: 0

Views: 76

Answers (1)

potashin
potashin

Reputation: 44581

Use

 onsubmit="ShowForm();return false"

Instead of

 onsubmit="return ShowForm();"

Adding return false will prevent page from reloading, removing return from return ShowForm(); will allow javascript to run return false after ShowForm().

Example

Upvotes: 1

Related Questions