user8200327
user8200327

Reputation:

Combining strings in Javascript

I'm experimenting with Javascript and I created a simple HTML page with two fields, a button, and another field that should be the combination of the first two fields.

However, my Javascript is not working. Here are my files:

<!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>
  <h2>My First Web Page</h2>
  <p id="first">My First Paragraph.</p>
  <p id="second">My Second Paragraph.</p>
  <input onclick="myFunction()" type="submit" value="Combine" />
  <p id="third">Concatenate first and second.</p>
</body>
</html>

and the Javascript

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

  var third = first + " " + second;
  document.getElementById("third").value = third;

}

Alternatively, I'm testing it on this Codepen template

Upvotes: 1

Views: 84

Answers (4)

Sinisag
Sinisag

Reputation: 1358

You must declare it as function. And value is not the right property to modify, but you can use 'innerHTML' or example. Here is the updated, working JS.

function myFunction(){
    var first = document.getElementById("first").innerHTML;
    var second = document.getElementById("second").innerHTML;
    var third = first + " " + second;
    document.getElementById("third").innerHTML = third;
}

Upvotes: 2

The problem here is that you are setting the value of the paragraph and not the html.

What you should do is use innerHTML instead of value.

Here is a stackoverflow discussion about the difference between value and innerHTML:

Upvotes: 1

jh314
jh314

Reputation: 27802

You can use textContent instead:

function myFunction(){
  var first = document.getElementById("first").textContent;
  var second = document.getElementById("second").textContent;

  var third = first + " " + second;
  document.getElementById("third").textContent = third;

}

Upvotes: 1

Steven Spungin
Steven Spungin

Reputation: 29071

Use innerText instead of value. And declare function correctly.

function myFunction() {
  var first = document.getElementById("first").innerText;
  var second = document.getElementById("second").innerText;
  var third = first + " " + second;
  document.getElementById("third").innerText = third;
}
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body>
  <h2>My First Web Page</h2>
  <p id="first">My First Paragraph.</p>
  <p id="second">My Second Paragraph.</p>
  <input onclick="myFunction()" type="submit" value="Combine" />
  <p id="third">Concatenate first and second.</p>
</body>

</html>

Upvotes: 2

Related Questions