John.P
John.P

Reputation: 657

Display first and lastname with JavaScript

I'm learning JavaScript and I'm trying to make it so the user is able to enter a name and lastname and then click a send button. When that happens the name and lastname is displayed on the the screen just bellow.

The problem is that it doesn't work. Nothing happens when the user clicks the send button.

Here is how I tired it.

HTML:

    <body>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br>
<input type="button" value="Send" onclick="MyFunction()">
    <div id="here"></div>    

<body>

JavaScript:

function MyFunction() {
    var first, second;
    first = document.getElementById("firstname").value;
    second = document.getElementById("lastname").value;

    document.GetElementById("here").InnerHTML = first;
    document.GetElementById("here").InnerHTML = second;
}

https://jsfiddle.net/7wu3gjqm/

Upvotes: 2

Views: 35878

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

This is your example worked fine after some changes :

HTML:

<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">

JS:

myFunction = function() {
    var first = document.getElementById("firstname").value;
    var second = document.getElementById("lastname").value;

    document.getElementById("here").innerHTML = first+" "+second;
}

Find your example here : jsFiddle.

Upvotes: 8

Robert Lee
Robert Lee

Reputation: 439

You wanted this as your output code:

document.getElementById("here").innerHTML = first + " " + second;

The G and I should be lower case and you should output both first and last names at the same time using string concatenation. Note though, that this will have XSS vulnerabilities.

Also, change your input name attributes to id attributes.

Upvotes: 5

taxicala
taxicala

Reputation: 21759

You are using getElementById but you dont have any element with the given Ids, I believe you've forgot to add id's to your input elements:

<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">

You might also want to change GetElementById for getElementById as js is case sensitive.

Upvotes: 1

Related Questions