admin管理员组

文章数量:1410717

I own a canvas website and want my customers to be able to enter a custom length of the canvas within a set range.

Say the range for the product is:

  • Minimum: 10 cm
  • Maximum: 200 cm

Then in the text box they can enter any number between that range, but if they enter "215" then it should automatically go down to "200". Likewise if they enter "7" then it should automatically go up to "10"

I own a canvas website and want my customers to be able to enter a custom length of the canvas within a set range.

Say the range for the product is:

  • Minimum: 10 cm
  • Maximum: 200 cm

Then in the text box they can enter any number between that range, but if they enter "215" then it should automatically go down to "200". Likewise if they enter "7" then it should automatically go up to "10"

Share asked Jun 20, 2011 at 15:45 MichaelMichael 2352 gold badges6 silver badges17 bronze badges 1
  • Input text fields have a maxlength attribute, but there's no minlength. You can put some javascript in there to detect insufficient data, as long as you do the same check server-side afterwards. – Marc B Commented Jun 20, 2011 at 15:48
Add a ment  | 

3 Answers 3

Reset to default 6
document.getElementById('textBoxID').onchange = function(){
      if(this.value > 200){
           this.value = 200;
      }
      if(this.value < 10){
           this.value = 10;
      }
}

Here is a fiddle example: http://jsfiddle/maniator/qwFN6/

<input type="text"
    onchange="this.value = (this.value > 215) ? 215 : ((this.value < 10) ? 10 : this.value);">

Find below jQuery based code

   <script type="text/javascript" src="jquery-1.5.1.js"></script>
    <style>
    #customForm input.error{
        background: #f8dbdb;
        border-color: #e77776;
    }
    </style>
    <script type="text/javascript">
    $(document).ready(function(){
        //global vars
        var form = $("#customForm");    
        var canvas = $("#canvasID");
        var canvasInfo= $("#canvasInfo");
        //On blur   
        canvas.blur(validateCanvas);    

        //On Submitting
        form.submit(function(){
            if(validateCanvas())
                return true
            else
                return false;
        });

        function validateCanvas(){
            //if it's NOT valid
        if(canvas.val()< 10 || canvas.val()>200){
            if(canvas.val()< 10) {
                canvas.val('10');
            }
            if(canvas.val()>200) {
                canvas.val('200');
            }
                canvas.addClass("error");
                canvasInfo.text("We want canvas Minimum: 10 cm and Maximum: 200 cm");           
                return false;
            }
            //if it's valid
            else{       
                canvas.removeClass("error");
                canvasInfo.text("");
                return true;
            }
        }   
    });
 </script>

本文标签: phpSetting a maximum and minimum value for text boxStack Overflow