简体   繁体   中英

Javascript: Allow Only Values less than input initial value

on my form, I have many text input fields with pre-filled decimal values, the user can edit the values before submitting the form.

I was wondering if there is anyway using javascript/jquery, to make each input allow only values less than its initial value.

I find it quite challenging, so I thought about posting it here. Thank you guys

Use jQuery Validation plugin 's max method .

Example:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and 23 or smaller.</title>
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">

</head>
<body>
<form id="myform">
<label for="field">Required, maximum value 23: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      max: $('your_input_selector').val()
    }
  }
});
</script>
</body>
</html>

This may help you:

 var initialValue = $("#myTextbox1").val() $("#myTextbox1").on("input", function() { if($("#myTextbox1").val() > initialValue) { $("#myTextbox1").val(initialValue); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="myTextbox1" type="text" value="5"/> 

This solution converts the input into a number, prevents default form action, checks if the input value is a number and if not it alerts the user and resets the default input value, checks to see if the new value is less the the original and if it is not it resets the input to the original value.

HTML

<form id="myForm" action="">
    <input type="text" id="myValue" value="5" />
    <input type="button" id="myButton" value="validate" />
</form>  

JavaScript

var origVal = $('#myValue').val();

$('#myButton').on('click', function(e) {
        var getVal = Number($('#myValue').val());
        e.preventDefault();

        if (isNaN(getVal) === true) {
            alert('The input value has to be a number.');
            $('#myValue').val(origVal);
        }

        if (getVal > origVal) {
            alert('The input value has to be less than the original value of ' + origVal);
            $('#myValue').val(origVal);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM