1

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

3
  • 2
    Paragraphs don't have the value attribute. Form elements do Commented Aug 25, 2018 at 16:05
  • In your codepen your js has a syntax error - click the error icon to see it Commented Aug 25, 2018 at 16:05
  • 1
    Your syntax for declaring a function is incorrect, it should be function myFunction() { Commented Aug 25, 2018 at 16:05

4 Answers 4

2

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>

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

Comments

2

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;
}

Comments

1

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;

}

Comments

1

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:

Comments

Your Answer

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