0

Why is my code not working correctly?

(Sorry, I'm not good in English to explain, not my fault)

HTML:

<input type="text"  id="euro" /> € = <span id="coins"></span> Miitomo Coins

<button onclick="ok()">Convert</button>

JS code:

function ok() {
    document.getElementById("coins").innerHTML = a + 100;
}

var a = document.getElementById("euro").value;
1
  • You probably want to get the value from the input field when you click the button, so move it into the ok() method. Commented May 8, 2016 at 8:03

4 Answers 4

1

Two problems:

  • You must define the input field and not the value
  • You must use parseInt()

Code:

var input = document.getElementById("euro");
function ok()
{
    document.getElementById("coins").innerHTML = parseInt(input.value) + 100;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Where do I need to put the parseInt()?
@TheUserNo2017 on the input.value
1

First, grab the value of the field when the button is clicked so you have the current content:

function ok() {
    var val = document.getElementById( "euro" ).value;
    ...
}

Then, convert the value that you grabbed to a number. Content in the DOM is always a string:

function ok() {
    var val = document.getElementById( "euro" ).value;
    var eurosNumber = Number( val );
    ...
}

Note that I'm using Number instead of parse*.

I'm assuming that you may type either an integer (1, 20, 25, etc.) or a fractional number (1.50, 10.25, 20.34, etc.) into the field.

You can do the same conversion with parseFloat or parseInt but this is more explicit that you're converting [some string] to a Number.

Just watch out: if the string isn't a valid number, there will be an error (Number( [not a number] ) will return NaN)!

Finally, do your addition:

function ok() {
    var val = document.getElementById( "euro" ).value;
    var eurosNumber = Number( val );

    document.getElementById( "coins" ).innerHTML = eurosNumber + 100;
}

1 Comment

I wouldn't say that Number is more "explicit" but I would argue that if decimal input is expected, it's usage (or just unary coercion) is favourable over parseInt due to quirky historical behaviours cross-browser - and the fact that best practice dictates you should always specify the radix.
0

You need to read the input value in the ok function and to use parseInt or parseFloat:

<input type="text"  id="euro" /> € = <span id="coins"></span> Miitomo Coins
<button onclick="ok()">Convert</button>

JavaScript:

function ok() {
      var a = parseFloat(document.getElementById("euro").value);
    document.getElementById("coins").innerHTML = a + 100;
}

JsFiddle here

Comments

-1
var a = parseInt(document.getElementById("euro").value);

Use parseInt()

Comments

Your Answer

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