How to enabled button, when the actual amount entered
lets say i have 100 minimum and 200 maximum
i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled
when user enters more than 200 do the same echo error
user has to enter 100 and above but not exceed maximum
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
var textBox = $('#Textfield').val();
if((textBox >= 100) || (textBox <= 200) ){
$('.disabledButton').prop("disabled", false);
} else {
$('#error').text('actual amount needed');
return false;
}
});
</script>
If you are using html 5, you don't need JavaScript. The best way to do this is to set this field to a number, like
<input type="number" min="100" max="200" placeholder="value in 100-200" id="Textfield" />
By setting min and max values, the form will not submit if the value in this field is not in that range
There's a number of reasons your code is not working:
.val() is always text, so you are (would be) comparing "15" with 100 and 200 and it would pass, convert to an integerThe main issue is:
if((textBox >= 100) || (textBox <= 200) ){
if the textbox value is greater than 100 OR it's less than 200, well, all values follow this rule: eg 1 is less than 200, so passes, 3000 is more than 100, so passes.
This should be
if((textBox >= 100) && (textBox <= 200) ){
Giving updated snippet:
$('#Textfield').keyup(function() {
var textBox = $('#Textfield').val() * 1;
if ((textBox >= 100) && (textBox <= 200)) {
$('.disabledButton').prop("disabled", false);
$('#error').text('ok');
} else {
$('.disabledButton').prop("disabled", true);
$('#error').text('actual amount needed');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
$('#Textfield').on('keyup',function(){
//every time a key is pressed we count the total number of characters in the field
var charLength = $(this).val().length;
//if they are equal to or above 100 and equal to or below 200 we disable the disabled button property else we disable the button again
if(charLength >= 100 && charLength <= 200){
$('.disabledButton').prop('disabled',false)
}else{
$('.disabledButton').prop('disabled',true)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>