Reputation: 88
When a user selects the specific product from the option box I want to put validation in width text box that user only enter a value between 10 to 200
I am done with getting selected value but not able to validate it properly
I also use HTML5 attributes min and max but not working.
$(function() {
$('#product').change(function() {
if ($('#product').val() == 'Copper flat') {
if ($('#width').val() >= 10 && $('#width').val() <= 200) {
alert("Value must be between 10 to 200")
}
} else if ($('#product').val() == 'Fabricated Copper Busbar') {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="product" id="product" class="form-control">
<option selected="selected" value="">Product type</option>
<option value="Copper flat">Copper flat</option>
<option value="Fabricated Copper Busbar">Fabricated Copper Busbar</option>
<option value="Fabricated aluminium Busbar">Fabricated aluminium Busbar</option>
</select>
Upvotes: 1
Views: 1184
Reputation: 337656
To set the min
and max
values of an input
use jQuery's prop()
method. Also note that you can DRY up the logic by putting the values associated with each option
in data
attributes on the element which can easily be read when the change
event occurs. Try this:
$(function() {
var $width = $('#width');
$('#product').change(function() {
var $selected = $(this).find('option:selected');
$width.prop({
min: $selected.data('min'),
max: $selected.data('max')
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<select name="product" id="product" class="form-control">
<option selected="selected" value="">Product type</option>
<option value="Copper flat" data-min="10" data-max="200">Copper flat</option>
<option value="Fabricated Copper Busbar" data-min="100" data-max="2000">Fabricated Copper Busbar</option>
<option value="Fabricated aluminium Busbar" data-min="50" data-max="75">Fabricated aluminium Busbar</option>
</select>
Width: <input type="number" id="width" required />
<button>Submit</button>
</form>
Upvotes: 1