Is it possible to use `event.preventDefault()` with a `select` element with jQuery?
I have dropdowns which are dependent on other dropdowns.
I decided to calculate the dependencies on click, except it has a nasty side effect of showing option elements, then they quickly disappear and the dropdown list resizes.
I wondered if I could use event.preventDefault() on click, and then call the click() event manually after I have calculated the possible options.
It didn't seem to work.
What is the best way around this?
Here is my jQuery
var $selects = $('form#main select');
$selects.click(function(event) {
    var $thisSelect = $(this);
    event.preventDefault(); // Doesn't cancel anything
    // Get the other selected values
    var selectedIndexes = [];
    $selects.not($thisSelect).each(function() {
        var index = $(this)[0].selectedIndex;
        selectedIndexes.push(index);
    });
    // I think this is where the problem lies -
    // it is my lazy way of showing them all again before I hide
    // what needs to be开发者_运维技巧 hidden
    $selects.find('option').show();
    // Remove them from this dropdown
    $.each(selectedIndexes, function(i, index) {
        $thisSelect.find('option').eq(index).hide();
    });
}).click();
Thanks!
Update
Sorry for any confusion, you can see this behaviour on JSBin.
You can not select one from the other - i.e. they can never have the same value.
In my Firefox 3.6.6, you will see the ugly jump between it calculating what it may display.
I realise for 2 selects only I could use .siblings().hide(), but it won't work if I need more than 2 (which I will later).
My ideal behaviour would be to click the select and have it show with no jump the available options. I think maybe my show() is the culprit, however it keeps the code simple.
I am still not sure that i am fully understanding your question. but this may work for you. If you have problems, i will be glad to help you, but i would need a better explanations.
- http://jsfiddle.net/kn73G/
HTML
<select id="left">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<select id="right">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
JavaScript
$(document).ready(function() {
    var left = $("#left");
    var right = $("#right");
    left.change(function(){
        if (right.val() == $(this).val()) {
            alert("error");
            $(this).attr("selectedIndex", "0");
        }
    });
    right.change(function() {
        if (left.val() == $(this).val()) {
            alert("error");
            $(this).attr("selectedIndex", "0");
        }
    });
});
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论