Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have select options which are dynamically created. What I want to do is, when the number of rooms is 0, the number of people option to be disabled, otherwise to be enabled. I tried a couple of things but they work only for the first select. How can I get them to work for all dynamically created selects?

HTML
<select name="numberOfRooms" id="numberOfRooms"
   th:field="*{rooms[__${rowStat.index}__].numberOfRooms}">
   <option value="0">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>
<select name="numberOfPeople" id="numberOfPeople" disabled="disabled"
   th:field="*{numberOfPeople}">
   <option value="0">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>


What I have tried:

JavaScript
$(document).ready(function () {
    $('#numberOfRooms').on('change', function () {
        let val = $('#numberOfRooms').val();
        console.log(val);
        if (val == 0) {
            $('#numberOfPeople').attr('disabled', true);
        } else {
            $('#numberOfPeople').attr('disabled', false);
        }
    })
})


I also tried with onchange() but same result.
Posted
Updated 7-Feb-22 0:00am

1 solution

Read the "Attributes vs. Properties" section of the documentation[^].

The value of the disabled attribute is the string "disabled".

The value of the disabled property is true or false.

Change your code to use .prop("disabled", false) instead of .attr("disabled", false).

Also read the documentation for the ready event[^]: the $(document).ready(...) syntax has been deprecated since jQuery v3. The recommended version is simply $(...), which does the same thing.
JavaScript
$(function () {
    $('#numberOfRooms').on('change', function () {
        let val = $('#numberOfRooms').val();
        console.log(val);
        if (val == 0) {
            $('#numberOfPeople').prop('disabled', true);
        } else {
            $('#numberOfPeople').prop('disabled', false);
        }
    })
})
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900