From a table row with two dropdowns, get selected value & which drop-down changed

后端 未结 2 475
Happy的楠姐
Happy的楠姐 2021-01-07 02:23

I am trying to update two cascading drop down inside a table there are many answers on SO for drop downs, but I was unable to find help on cascading updates

相关标签:
2条回答
  • 2021-01-07 02:48

    Assuming that you can't identify dropdwns by class or anything. Assuming that every time you change the value in a dropdown you want to update the other dropdown on the same row. Assuming that you have only two dropdowns per row:

    $('table').on('change', 'select', function() {
        var $current_dropdown = $(this),
            $other_dropdown = $(this).closest('tr').find('select').not(this);
    
        /// perform any task you need with current and other dropdown
    
    });
    
    0 讨论(0)
  • 2021-01-07 03:02

    You need to give both your <select> elements class names and use relative selectors to select the associated element in the same row.

    Assuming your html is

    <table id="table"> // give this an id attribute
        <tbody>
            <tr>
                <td><select class="country" ....> ..... </select></td>
                <td><select class="state" ....> ..... </select></td>
            </tr>
        </tbody>
    </table>
    

    Then your script will be

    $('#table').on('change', '.country', function() {
        var selectedValue = $(this).val();
        var row = $(this).closest('tr'); // get the row
        var stateSelect = row.find('.state'); // get the other select in the same row
        // make you ajax call passing the selectedValue to your controller
        // in the success callback, update the options of stateSelect 
        $.ajax({
            url: ...
            data { id: selectedValue },
            ....
            success: function(data) {
                stateSelect.empty();
                $.each(data, function(item, index) {
                    stateSelect.append($('<option></option>').val(iem.ID).text(item.Name));
                }
            }
        });
    }
    

    Refer also better way to load 2 dropdown in mvc for details of the code for populating cascading dropdownlists (consider caching the options as per the 2nd code example to avoid repeated ajax calls)

    0 讨论(0)
提交回复
热议问题