Search code examples
javahtmljqueryspring-bootthymeleaf

Enabling the data from second dropdown when it selected in the first dropdown with jQuery


How can I write a jQuery function that enables the value from second dropdown only if a value is selected on the first dropdown?

As I selected Shiva in first drop down it should be disabled from 2nd drop down.

fist drop down value must not be equal to 2nd dropdown.

<select class="form-control" id="select2">
   <option value="1556456">Shiva</option>
   <option value="34234">Disha</option>
</select>

<select class="form-control" id="select3">
    <option value="1556456">Shiva</option>
    <option value="34234">Disha</option>
</select>

Solution

  • Not sure if this is what you mean. Let me know. You can use a .find and .filter on it.

    $('select').on('change', function() {
        $('option').prop('disabled', false);
        $('select').each(function() {
            var val = this.value;
            $('select').not(this).find('option').filter(function() {
                return this.value === val;
            }).prop('disabled', true);
        });
    }).change();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
    <select class="form-control" id="select2">
       <option value="1556456">Shiva</option>
       <option value="34234">Disha</option>
    </select>
    
    <select class="form-control" id="select2">
        <option value="1556456">Shiva</option>
        <option value="34234">Disha</option>
    </select>
    
    </form>