-1

how to set range in text field for numeric up and down?More over the value in the text box can be increase and decrease using up and down key also?

i am using textbox with two images(up and down) like (for increment) and (for decrement) here how can i set range 0 to 100 (i am working in struts)

Hari kanna
  • 2,461
  • 6
  • 29
  • 43
  • i am using textbox with two images(up and down) like (for increment) and (for decrement) here how can i set range 0 to 100 (i am working in struts) – Hari kanna Feb 17 '11 at 05:39

2 Answers2

0

Look at the HTML5 input made for this.

<input type="number"
       min="0"
       max="10"
       step="2"
       value="6">

If you want to use JavaScript, try...

var input = document.getElementById('your-number-input'),
    lowerBound = 0,
    upperBound = 10;

input.onkeyup = function(event) {
    event.preventDefault();

    var value = parseInt(input.value, 10),
        keyCode;

    if (isNaN(value)) {
        value = 0;
    }

    if (window.event) {
        keyCode = event.keyCode
    } else if (event.which) {
        keyCode = event.which
    }

    if (keyCode == 38) {
       value++;
    } else if (keyCode == 40) {
       value--;  
    }

    if (value > upperBound) {
        value = upperBound;
    } else if (value < lowerBound) {
       value = lowerBound;
    }

    input.value = value;
}

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • i am using textbox with two images(up and down) like (for increment) and (for decrement) here how can i set range 0 to 100 (i am working in struts) – Hari kanna Feb 17 '11 at 05:41
  • @Hari kanna The code to do that is above, see references to `upperBound` and `lowerBound`. – alex Feb 17 '11 at 06:06
0

Edit: as per Alex's answer, there is a field in HTML5, so my statement about there not been one is incorrect.

There is no numeric up down field in HTML, so I'm presuming you're using a javascript implementation ( something like this http://www.htmlforums.com/client-side-scripting/t-help-with-numericupdown-control-59399.html ).

Have the onclick event for the up and down buttons trigger a JavaScript function. In this function have it check the value that it is changing to using an if statement, and if it's too large, don't increase it, and vice versa.

You'd want something along the lines of below. I haven't used javascript for a little while so I can't vouch for the correct syntax.

if (document.getElementById("input1").value < 5)
{
    document.getElementById("input1").value++
}

As for key presses, check out http://www.w3schools.com/jsref/event_onkeypress.asp . Use this to trigger the same functions that the up and down buttons on the web page trigger.

joshhendo
  • 1,964
  • 1
  • 21
  • 28