Reputation: 15
I am trying to make input enable when some option is selected from the drop-down
I wrote code for solving this problem, but it doesn't work. Here is my code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<select class="form-control" id="dropDown">
<option id="n" value="0"> Тип N </option>
<option id="p" value="1"> Тип P </option>
<option id="c" value="2"> Тип C </option>
<option id="v" value="3"> Тип V </option>
<option id="t" value="4"> Тип T </option>
<option id="s" value="5"> Тип S </option>
</select>
<div>
<label class="control-label">
<span th:text="#{size}"></span>
</label>
<input id="size" type="text" class="form-control" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script th:inline="javascript">
$('#dropdown').change(function() {
if( $(this).val() === 1) {
$('#size').props( 'disabled', false );
} else {
$('#size').props( 'disabled', true );
}
});
</script>
</body>
</html>
So I'm expecting that when I select the option "Тип P" input (id="size") should be enabled, if other options selected it should stay disabled
Upvotes: 0
Views: 773
Reputation: 68933
===
is strictly equality operator, it checks both value and type, and as the value of an element is always a string, comparing it to a number will always fail.
Please Note: You also have typo in props
, should be prop
. The attribute id used in the control (dropDown
) and code (dropdown
) does not match with each other.
Change
if( $(this).val() === 1) {
To
if( $(this).val() === "1") {
Upvotes: 2
Reputation: 36594
You are making three mistakes:
this.val()
returns a string but you are comparing it with a number 1
.$('#dropdown')
should be $('#dropDown')
prop
instead of props
You are setting true
and false
so you can direclty pass the condition to prop()
$('#dropDown').change(function() {
$('#size').prop( 'disabled', $(this).val() !== "1" )
});
$('#dropDown').change(function() {
$('#size').prop( 'disabled', $(this).val() !== "1" )
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<select class="form-control" id="dropDown">
<option id="n" value="0"> Тип N </option>
<option id="p" value="1"> Тип P </option>
<option id="c" value="2"> Тип C </option>
<option id="v" value="3"> Тип V </option>
<option id="t" value="4"> Тип T </option>
<option id="s" value="5"> Тип S </option>
</select>
<div>
<label class="control-label">
<span th:text="#{size}"></span>
</label>
<input id="size" type="text" class="form-control" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script th:inline="javascript">
</script>
</body>
</html>
You can shorten your function by using ternary operators.
Upvotes: 1