How to find out and compare the value in the input field?

For example: There is an input with the name q and with a value of 5. The person has changed 5 to 3 and an alert is displayed for him, then less than 5 cannot be entered.

    3 answers 3

    <input type="text" name="q" value="" onchange="changeQ(this)" /> ... <script type="text/javascript"> function changeQ (e) { if (e.value < 5) { alert("Меньше 5 в поле вводить нельзя"); } } </script> 
    • Both options work only after reloading the page (in the opera), so you can do with PHP. And I would like to asynchronously ... using JS - banyman
    • Well, if this is the only input and the form is submitted enter, then you can do onkeyup="changeQ(this)" - chernomyrdin
    • And if I enter a string in input? ;) - Zowie
    • not "e.value", but "e.target.value" - Pax Beach
    • No, in this case, the changeQ function as an argument e receives not Event , but HTMLInput . As a result, HTMLInput target property and there will be an error. - chernomyrdin

    I threw it using prototype (I don't like jquery, it was lazy on the native)

     <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="prototype.js"></script> <script> Event.observe(window,"load", function() { function initInputValidation(el) { el.observe("keyup", function(){ var info = $$(".info")[this.infoIndex]; var value = parseInt(this.value); if(isNaN(value)) { info.update("Введите число"); info.setStyle({ color:"red" }); } else { if(value < 5) { info.update("меньше 5 вводить нельзя"); info.setStyle({ color:"red" }); } else { info.update("ок"); info.setStyle({ color:"green" }); } } }) } var q = document.getElementsByName("q"); var qTotal = q.length; for(var i=0; i<qTotal; ++i) { q[i].infoIndex = i; initInputValidation(q[i]); } }) </script> </head> <body> <input type="text" name="q" value="5"> <span class="info" style="color:green">ok</span> <br> <input type="text" name="q" value="5"> <span class="info" style="color:green">ok</span> </body> </html> 

    Naturally, such input can be as much as you like, did not use alert because it is a stone age and, personally, I (I assure I am not special in this sense) they are terribly besy

      Simply (assume there is a single input tag with the value of the name attribute some equal)

       <html> <head> <script> window.onload = function() { tagList = document.getElementsByName('some'); if (tagList[0].value > 3) alert(">3"); } </script> </head> <body> <input name="some" type="text" value="4" /> </body> </html> 
      • There are several such inputs on the page - banyman