1

我想检查一组选择框,看看它们在单击按钮后是否发生了变化。

<select name="data[model][that]" class="location_dropdown">
    <option value="value1">value 1</option>
    <option value="value2">value 2</option>
    <option value="value3" selected="selected">value 3</option>
</select>

<select name="data[model][that]" class="location_dropdown">
    <option value="value1">value 1</option>
    <option value="value2" selected="selected">value 2</option>
    <option value="value3">value 3</option>
</select>

<select name="data[model][other]" class="location_dropdown">
    <option value="value1" selected="selected">value 1</option>
    <option value="value2">value 2</option>
    <option value="value3">value 3</option>
</select>

$(document).ready(function() {

    $('#update-selected-btn').click(function(){
        $('.location_dropdown').each(function(){



        });
    });

    if state hasnt changed on any drop downs alert("nothing selected")

});

显然不能使用 onchange ,因为我想在触发按钮单击时检查更改。我在考虑可能构建一组值并将它们相互检查,但想知道是否有另一种解决方案。

更新:

我确实尝试过,但语法不正确。

$('.location_dropdown').each(function(){
    if ($(this + " option:selected").prop('selected') == 'selected'){
       changed++;
    }
});
4

2 回答 2

4

您可以使用全局变量来监视选择的选择变化。

现场演示

var dropdownChanged = false;
$('.location_dropdown').change(function(){    
     dropdownChanged = true;    
});


$('#update-selected-btn').click(function(){
    dropdownChanged = false;
});
于 2013-05-03T18:06:25.003 回答
1

You don't need to use a global variable, when something is selected just add a data attribute to the select and in your button click look for the dropdown with the attributes.

演示

     $('#update-selected-btn').click(function(){
        var selected = $('.location_dropdown[data-changed]'); //select the changed ones
        if(selected .length == 0)
        {
           alert('nothing selected'); return
        }
        selected .each(function(){
             //do something with them.
        });
    });

    $('.location_dropdown').change(function(){
        $(this).attr('data-changed', 'true'); //Add attribute to the selected ones.
    });
于 2013-05-03T18:14:45.033 回答