0

I was thinking about forcing people to be only capable of writing the numbers between 0-100 (because of the maximum number attained via a percentage is 100%).

Is there a way to force people to input a number between 0-100%? I am already restricting them to 3 digits using javascript.

I am looking to using javascript for this.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
M.Sidim
  • 303
  • 3
  • 4
  • 15
  • Just parse it and check if it's in that range.. – Jordan Kaye Jul 15 '13 at 14:18
  • Can you post any code to show what you have tried? – cfs Jul 15 '13 at 14:18
  • `if (val <= 100 && val >= 0) {}` – Ian Jul 15 '13 at 14:21
  • @Jordan: I looked up what parse is, and I don't see the relevance, but I assume that I am not looking on the right sites. I usually would use things like parseInt or parseFloat. So, I'm not looking in the right place, am I? – M.Sidim Jul 15 '13 at 14:40
  • @cfs, the code I had was pretty much the same as Ian. – M.Sidim Jul 15 '13 at 14:40
  • @M.Sidim Could you post your code in your question? That will help us provide an answer for you. – cfs Jul 15 '13 at 14:41
  • @Ian, thank you. I meant on input itself. I just saw what Yann posted. I did not know that I could do this on input like this. I knew for js on validation, but not on input. However, I am grateful for your help :D – M.Sidim Jul 15 '13 at 14:41

2 Answers2

1

You could use a number input <input type="number" min="0" max="100">, but it won't work in all browsers so you'll have to complement it by some javascript in order to double check the value is correct.

Yann
  • 2,211
  • 1
  • 15
  • 14
  • I did not know you could do that on input like that. This is awesome :) But yeah, you're right I'll still validate it afterwards. – M.Sidim Jul 15 '13 at 14:42
1

You could use the Range type input element, which appears as a slider.

<input type="range" name="percentage" min="0" max="100">

Or you could run a validation function on the onchange or onkeyup events, that checks for a value more than 100.

<input type="text" name="percentage" onkeyup="validate(this);">

function validate(el){
    if(el.value > 100){
        el.value = 100;
    }
}
Ben
  • 903
  • 1
  • 9
  • 13
  • Oh my, I did not see your answer. Thank you posting. I will definitely compare Yann's method and yours. It appears that yours might be just as interesting! As for the validation, I am definitely going to run it :) – M.Sidim Jul 15 '13 at 14:52
  • You're welcome! Perhaps consider voting up the answer which ended up suiting you best :) – Ben Jul 16 '13 at 05:33
  • Oh yes, I can do that now! I forgot I have a rep of 15+ now :D – M.Sidim Jul 16 '13 at 13:14