Michael Hampshire Michael Hampshire -4 years ago 75
HTML Question

Changing text in a paragraph

I'm trying to change the text of a paragraph and everything that I can see in my code should work but it's not changing the text?

I've looked at multiple posts on stackoverflow already and I've implemented what they say but my paragraph is still not changing. I'm trying to change the paragraph based on what the user inputs in a form text box. Am I missing something?



function ticketPrice() {

var age = document.getElementById("age");
var newAge = parseInt(age);

if (newAge <= 5) {
document.getElementById("price").innerHTML = "Free";
} else if (newAge >= 6 && newAge <= 17) {
document.getElementById("price").innerHTML = "Half Price";
} else if (newAge >= 18 && newAge <= 55) {
document.getElementById("price").innerHTML = "Full Price";
} else if (newAge >= 55) {
document.getElementById("price").innerHTML = "$2 off";
} else
document.getElementById("price").innerHTML = "ERROR"
}

<p>Please enter your age to find the price of your movie ticket.</p>
<form id="form1" action="" method="POST">
Please enter your age:<br>
<input type="text" name="age" value=""><br><br>
<p id="price">Hello</p>
<input type="button" onclick="ticketPrice()" value="submit">
</form>




Answer Source

You're successfully updating the element, but then the form submission occurs (because the button is type="submit"), which reloads the page from the server, and so the old text shows up again.

If you don't want the form to submit, change the type to button.

Two other problems with the code:

  1. You're looking up the age element by id, but it doesn't have an id, it just has a name. Add id="age" to it.

  2. You're using the element itself when parsing to integer; you want to use its value (add .value).

So (see comments):

function ticketPrice() {

  // *** .value on the next line
  var age = document.getElementById("age").value;
  var newAge = parseInt(age);

  if (newAge <= 5) {
    document.getElementById("price").innerHTML = "Free";
  } else if (newAge >= 6 && newAge <= 17) {
    document.getElementById("price").innerHTML = "Half Price";
  } else if (newAge >= 18 && newAge <= 55) {
    document.getElementById("price").innerHTML = "Full Price";
  } else if (newAge >= 55) {
    document.getElementById("price").innerHTML = "$2 off";
  } else
    document.getElementById("price").innerHTML = "ERROR"
}
<p>Please enter your age to find the price of your movie ticket.</p>
<form id="form1" action="" method="POST">
  Please enter your age:<br>
  <!-- *** id="age" *** -->
  <input type="text" name="age" id="age" value=""><br><br>
  <p id="price">Hello</p>
  <!-- *** type=button *** -->
  <input type="button" onclick="ticketPrice()" value="submit">
</form>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download