2

I am learning HTML/JavaScript and am writing a simple site to test what I've learned so far. I am trying to get the firstname and lastname entered by the user from an input form and then pass these names to a JavaScript function but for some reason, all I see in my popup window is:

Hello [object HTMLInputElement]

This is my html code:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Daynesh's Test Site</title>
    <script>
        function addUser(first, last)
        {
        alert("Hello " + first);
        }
    </script>
    </head> 
    <body>
    <h1>Registered Users</h1>
    <p>Enter user name:</p>
    <form>First name: <input type="text" name="firstname">
      Last name: <input type="text" name="lastname">
        <input type="submit" value="Submit" onclick="addUser(firstname,'right')">
    </form>
    <hr>
    <h3>Output</h3>
    </body>
    </html>

Can someone please explain what I'm doing wrong? I'm sure its something very simple that I'm not understanding here.

Thanks in advance!

0

2 Answers 2

5

in your code

onclick="addUser(firstname,'right')"

firstname is nothing you don't define it before so you should define it in javascript or get value from input directly this your code after fix

  <!DOCTYPE html>
<html>
<head>
    <title>Daynesh's Test Site</title>
<script>
    function addUser(first, last)
    {
    alert("Hello " + first);
    }
</script>
</head> 
<body>
<h1>Registered Users</h1>
<p>Enter user name:</p>
<form>First name: <input type="text" name="firstname" id="firstname">
  Last name: <input type="text" name="lastname">
    <input type="submit" value="Submit" onclick="addUser(document.getElementById('firstname').value,'right')">
</form>
<hr>
<h3>Output</h3>
</body>
</html>

i hope my answer help you

Sign up to request clarification or add additional context in comments.

Comments

2
document.getElementByName('firstname').value

See a more detailed answer at: JavaScript: how to get value of text input field?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.