<html>

    <head>
        <title>Hell WOrld</title>

    </head>

    <body>

        <form method = "get" action = "index.html">
            <input type = "text" name = "username" />
            <input type = "submit" value = "submit">
        </form>

        <script type = "text/javascript">

            document.getElementByName("username").onsubmit = alert("Hello World");

        </script>

    </body>

</html>

In the code, when ever you click the submit button, it says hello world, but how come the event is not triggered?

Recommended Answers

The code will depend on what exactly you are trying to accomplish. If you just want to produce an alert when the button is clicked, then just add an onclick event...

<html>
    <head>
        <title>Hell World</title>
    </head>
    <body>
        <form method = "get" action = "index.html">
            <input type = …
Jump to Post

All 2 Replies

The code will depend on what exactly you are trying to accomplish. If you just want to produce an alert when the button is clicked, then just add an onclick event...

<html>
    <head>
        <title>Hell World</title>
    </head>
    <body>
        <form method = "get" action = "index.html">
            <input type = "text" name = "username" />
            <input type = "submit" onclick="alert('Hello World');" value = "submit">
        </form>
    </body>
</html>

THe problem is I want to do form validation:

test.html

<html>

    <head>
        <title>Hell WOrld</title>

    </head>

    <body>

        <form method = "get" action = "index.html">
            <input type = "text" name = "username" />
            <input type = "submit" value = "submit" id = "button">
        </form>

        <noscript>
            <h3>You need javascript</h3>
        </noscript>

        <script type = "text/javascript" src = "work.js">
        </script>

    </body>

</html>

work.js:

function handle()
{
    if(this.value = "")
    {
        alert("You need to enter something.");
        return false;
    }
}

function init() {

    document.getElementById("button").onclick = handle;

}


window.onload = init;

What am I doing wrong?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.