0

I have figured out how to update my html dynamically based on the current input of a form. However, I am stumped with how to perform any math on this value (i.e. value*5), and display that result, instead of merely displaying the value in the form.

Here is a live example: https://dl.dropboxusercontent.com/u/14749627/happy2/number.html

Here is my JavaScript:

<script>
window.onload = function() {

var purchase_quantity = document.getElementById('purchase_quantity');
purchase_quantity.onclick = updateNameDisplay;
purchase_quantity.onclick = updateNameDisplay;
purchase_quantity.onclick = updateNameDisplay;
function updateNameDisplay() {
  document.getElementById('nameDisplay').innerHTML = this.value || "1";
 }
};
</script>
2
  • 1
    Why do you repeat purchase_quantity.onclick = updateNameDisplay;? Commented Aug 20, 2013 at 2:47
  • Have you tried document.getElementById('nameDisplay').innerHTML = this.value*5 || "1"; ? Commented Aug 20, 2013 at 2:49

4 Answers 4

1

Campari's solution works, but you should convert it to a Number explicitly as a good habit. If you tried to add instead, it wouldn't work as expected. Also, thanks to Oriol for pointing out the other problem.

var purchase_quantity = document.getElementById('purchase_quantity');
purchase_quantity.onclick = updateNameDisplay;

function updateNameDisplay() {
    document.getElementById('nameDisplay').innerHTML = 
        this.value.length ? Number(this.value) * 5 : "1";
}

demo

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

Comments

1

Ah, now I see the problem. The obvious solution

document.getElementById('nameDisplay').innerHTML = this.value*5 || "1";

doesn't work because if this.value is "0", then "0"*5 is 0, which is falsy, so "1" is returned instead.

Then, you can use something like

document.getElementById('nameDisplay').innerHTML = (this.value || "1") * 5;

or

document.getElementById('nameDisplay').innerHTML = this.value ? this.value*5 : "1";

depending on what you want.

Comments

0

To get your value x 5? Pretty simple:

document.getElementById('nameDisplay').innerHTML = this.value * 5 || "1";
                                                   ^^^^^^^^^^^^^^

Check out this fiddle.

Comments

0

If I get what you are saying correctly, then you want to store the elements data as a variable.

var result = this.value * 5; document.getElementById('nameDisplay').innerHTML = result;

If I misinterpreted your question please correct me.

1 Comment

Or you could do it simply like @Campari suggested. Id vote you up but I don't have reputation enough, just joined.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.