dstreet / dependsOn

a jQuery plugin for handling form field dependencies
http://dstreet.github.com/dependsOn
MIT License
106 stars 32 forks source link

Feature request: refresh selection when option hidden #40

Open dzschille opened 7 years ago

dzschille commented 7 years ago

When i remove options from a select list, and the selection is on one of this hidden options, the selection should be refreshed, so it is on a visible option.

Example:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="./dependsOn.min.js"></script>
</head>
<body>
    <div class="field field-numbers">
        <label>Number</label>
        <select name="numbers">
            <option>One</option>        
            <option>Two</option>
            <option>Three</option>
        </select>
    </div>
    <div class="field field-chars">
        <label>Char</label>
        <select name="chars">
            <option>A</option>        
            <option class="depend-B">B</option>
            <option>C</option>       
            <option>D</option>
        </select>
    </div>
<script>
$(function() {
        function checkSelectsOptionsVisibilty(selector)
        {
            if ($(selector + ' option:selected').is(':disabled')) {
                $(selector + ' option').each(function () {
                    if ($(this).css('display') != 'none') {
                        $(this).prop("selected", true);
                        return false;
                    }
                });
            }
        }

        $('.depend-B').dependsOn({
                '.field-numbers  select': {
                    values: ['One','Two']
                }
        }, {
                    onDisable: function() { checkSelectsOptionsVisibilty('.field-chars select');}
        });
});
</script>
</body>
</html>

Select char "B", then number "three". The selection "jumps" now to char "A", because "B" is now hidden.

It would save a lot of code lines on longer forms, if the functionality of checkSelectsOptionsVisibilty() would be somehow be included in dependsOn.