user1692342
user1692342

Reputation: 5237

Update Text in input box using Javascript

I have an input box which is written as shown below:

<input id="SlidingWindow" type="number" placeholder="50" class="span3">

This input box is part of a form and on clicking a submit button, I call a javascript function. I am trying to do a check if the number inputted is withing range. Incase it is not in range, I want to set the value in the box to a default value as shown below:

slidingWindow = document.getElementById("SlidingWindow").value;
    if (slidingWindow < 30) {
        slidingWindow = 30;     
    } else if (slidingWindow > 2000) {
        slidingWindow = 2000;       
    }
    document.getElementById("SlidingWindow").innerHTML = slidingWindow;

However on doing this, the text in the box does not change. Instead of innerHTML I tried value as well. That did not work either. What could be the possible solution?

Upvotes: 3

Views: 230

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

The problem here is that you are using .innerHTML to change the value of an input which is incorrect, you have to use .value instead, and to fire this test wrap your code into a function and attach it to the onchange event of your input, like this:

document.getElementById("SlidingWindow").onchange = function() {
  slidingWindow = document.getElementById("SlidingWindow").value;
  if (slidingWindow < 30) {
    slidingWindow = 30;     
  } else if (slidingWindow > 2000) {
    slidingWindow = 2000;       
  }
  document.getElementById("SlidingWindow").value = slidingWindow;
}
<input id="SlidingWindow" type="number" placeholder="50" class="span3">

You can test the Working Fiddle here.

Upvotes: 3

varad mayee
varad mayee

Reputation: 619

You have do one change only

 document.getElementById("SlidingWindow").innerHTML = slidingWindow;

replace this line by

document.getElementById("SlidingWindow").value= slidingWindow;

Other way is you can do this calling a function onchange

<input id="SlidingWindow" type="number" placeholder="50" class="span3" onchange="myFunction()">

function myFunction() {
    slidingWindow = document.getElementById("SlidingWindow").value;
    if (slidingWindow < 30) {
        slidingWindow = 30;     
    } else if (slidingWindow > 2000) {
        slidingWindow = 2000;       
    }
    document.getElementById("SlidingWindow").value = slidingWindow;
  }

Upvotes: 1

R3tep
R3tep

Reputation: 12854

Replace innerHTML by value

function foo() {
    slidingWindow = document.getElementById("SlidingWindow").value;
    if (slidingWindow < 30) {
        slidingWindow = 30;     
    } else if (slidingWindow > 2000) {
        slidingWindow = 2000;       
    }
    document.getElementById("SlidingWindow").value = slidingWindow;
  }
<input id="SlidingWindow" type="number" placeholder="50" class="span3" onchange="foo()">

Upvotes: 2

Related Questions