Skip to content Skip to sidebar Skip to footer

Instantiate A Variable Out Of Text Field Value In Javascript

So I have tried many different suggestions on how to get a value from an input text field and store it in a global variable. I am working on this game and it needs to take the valu

Solution 1:

you are not updating the score field.try this

functiondoFunction(ref)
 {
   score =document.getElementById("1").value;

   if (ref.value== "X")
    {
      randnum=Math.floor( 9*Math.random() ) + 1;
      ref.value=randnum;
      score = parseInt(score + ref.value, 10);
      document.getElementById("1").value = score;
   }
}

also you have to change the first alert to

if(score > 21)
  {
    window.alert ("You hit " + score + " You have lost");
  }

Solution 2:

There are two things you need to fix.

1: Your numbers are concatenating, which is making a "string" of numbers. So you need to multiply the numbers by 1.

2: You are not updating the HTML.

You should have:

if (ref.value == "X") {
    randnum = Math.floor( 9*Math.random() ) + 1;
    ref.value=randnum;
    //Multiply by 1 here to force the recognition of arithmetic instead of concatenation
    score = (score * 1) + (ref.value * 1);
    //You are missing the following line
    document.getElementById("1").value = score
}

Post a Comment for "Instantiate A Variable Out Of Text Field Value In Javascript"