开发者

Simple JavaScript issue involving forms and alerts

I'm trying to make a form which takes in a users name, and then when the submit button is pressed, an alert is displayed saying good morning, afternoon or evening (depending on time). I feel like I'm in spitting distance but I just can't get it to work, here is the related snippets of code:

<script type="text/javascript"> 
<!--
    function say_hello() {
        var date = new Date();
        var time = date.getHours();
        var name = document.forms["hello"]["name"].value;

            if (time < 12) {
                alert ("Good morning, "+name+"!");
            }

            else if (time > 12 && time < 18) {
                alert ("Good afternoon, "+name+"!")
            }

            else {
                alert ("Good evening, "+name+"!")
            }
        );
    }
// -->
</script>

and the HTML:

   开发者_如何学运维 <form name="hello" action=""> 
    <p> 
    What is your name?
    <input type="text" name="name" size="10">
    </input> 
    </p> 
    <p> 
    <input type="button" name="Submit" onclick="say_hello()" value="Receive Personal Message!">
    </input>
    </p> 
</form>

Thank you! :D


function say_hello() {
    var date = new Date();
    var time = date.getHours();
    var name = document.forms["hello"]["name"].value;

        if (time < 12) {
            alert ("Good morning, "+name+"!");
        }

        else if (time > 12 && time < 18) {
            alert ("Good afternoon, "+name+"!")
        }

        else {
            alert ("Good evening, "+name+"!")
        }
    //); //This causes a syntax error
}


You have a syntax error in your javascript. The ");" is unnecessary.

function say_hello() {
    var date = new Date();
    var time = date.getHours();
    var name = document.forms["hello"]["name"].value;

    if (time < 12) {
        alert ("Good morning, "+name+"!");
    }

    else if (time > 12 && time < 18) {
        alert ("Good afternoon, "+name+"!");
    }

    else {
        alert ("Good evening, "+name+"!")
    }
}


Fixing all your syntax errors, I would recommend you attached the event like this:

document.forms["hello"]["Submit"].onclick=say_hello;

Instead of onclick="..."

LIVE DEMO


In your function, there is a syntax error just after the last else {...}, there is an unnecessary );.

Try removing it, it should work!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜