0

I'm trying to do a simple code that such accepts data input into two text boxes (firstname and lastname) ad upon the user clicking a submit button the input data should get displayed on the screen. But I only get the first input data displayed. Why?

Here is my code:

<HTML>
<HEAD>
<TITLE>Forms With JavaScript</TITLE>
</HEAD>

<BODY>
<H1>Forms With JavaScript</H1>

<FORM name=myForm>
Enter your firstname: <INPUT TYPE="text" name="theFirstname"><BR><BR>
Enter your lastname: <INPUT TYPE="text" name="theLastname"><BR><BR>
<INPUT TYPE="submit" VALUE="Process" onclick="PrintFullName()">
</FORM>



<SCRIPT type="text/JavaScript">


function PrintFullName()
{   
    var fname = document.myForm.theFirstname;
    document.write(fname.value);

    var sname = document.myForm.theLastname;
    document.write(sname.value);
}

</SCRIPT>

</BODY>

</HTML>

1 Answer 1

2

Once you call document.write(), sname becomes undefined and throws an error. You can get around it by changing the function to the following:

function PrintFullName()
{   
    var fname = document.myForm.theFirstname;    
    var sname = document.myForm.theLastname;
    document.write(fname.value + " " + sname.value);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Psychemaster. I did the change as you suggested but now nothing gets displayed when I click the submit button.
Can't imagine why that would be, I used your code verbatim with my changed function and it worked perfectly fine...
Thank you Psychemaster, it worked now. One more thing though, I noticed that the output is sent to another page. Could you tell me why does that happen?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.