DanMc
DanMc

Reputation: 848

Javascript not accessing value in form

I'm learning javascript and xhtml for the first time at the moment and I currently have a problem which I have not been able to solve. I think it's a fairly simple fix, I just don't have to knowledge to be able to do it. Here's the javascript and how I'm attempting to call it from the xhtml.

This is in a javascript file called greet.js.

function tOD() {
timeOfDay = new Date
if (timeOfDay.getHours() < 5) {
    alert("Either go to bed, or go back to bed " + document.form[0].inputname.value);
}
else if (timeOfDay.getHours() < 11) {
    alert("Rise and shine " + document.form[0].inputname.value);
}
else if (timeOfDay.getHours() < 17) {
    alert("Good afternoon " document.form[0].inputname.value);
}
else {
    alert("And after a hard day at work you can relax at last, " +  document.form[0].inputname.value);
}
}

And here is where I'm trying to implement it in my xhtml.

<script type="text/javascript" src="greet.js"></script>
<FORM NAME = input>
Please enter your name:
<input type= "text" name = "inputName"/>
<input Type= Button NAME= "greeting" VALUE="ok" onClick="greet()"/>
</FORM>

The javascript works in that if I take away document.form[0].inputname.value it'll alert with the correct time of day when I press the button. So it must be the document.form[0].inputname.value, this must be wrong, I'm just unsure how to fix it. I've also tried using elements[0] instead of form[0] and also input and element[input] so I'm not sure what it could be...

Thanks, all help is appreciated.

Upvotes: 0

Views: 116

Answers (3)

ajimix
ajimix

Reputation: 992

You have some errors, I have made a working version for you. Please read it slowly and try to see your errors and fix them ;)

You can see it here: http://jsfiddle.net/3U5Qm/

Upvotes: 1

Saebekassebil
Saebekassebil

Reputation: 714

Your input

<input type="text" name="inputName"/>

is "camelCased", meaning the the N in 'name' is uppercase. You are using lowercase name attribute in your JavaScript

document.forms[0].inputname.value

inputname should be inputName. Notice that the forms collection is called document.forms and not document.form!

Besides this, you might want to use an ID on your input, so you could just access it using document.getElementById('inputid');

Upvotes: 2

gastonfartek
gastonfartek

Reputation: 348

else if (timeOfDay.getHours() < 17) {
    alert("Good afternoon " document.form[0].inputname.value);

you are missing a + sign

else if (timeOfDay.getHours() < 17) {
        alert("Good afternoon " + document.form[0].inputname.value);

Upvotes: 0

Related Questions