Javascript to hide selected option

前端 未结 4 1321
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 12:29

I have this code to hide selected options:

function connect()
{
    $(\".selectbox option\").show();
    $(\".selectbox\").each(function(i) { 
        var obj =          


        
相关标签:
4条回答
  • 2021-01-23 13:17

    You already have the selected option in your selector - no need to find option - as that will return you an empty array

    $('.selectboxes option:selected').hide();
    // get rid of .find('option')
    

    To exempt this value.. I'm guessing you're referring to the selected value.. you can use :not as undefined stated

    $(".selectbox option:not(:selected)").show();
    

    You can take out the inline onChange since you are using jQuery.. and bind the change event handler to the select elements on dom ready

    $(function(){
        $('select').change(function(){   
           var $sel = $('option:selected'); // get all selected options
           $('option').show(); // show all options
           $sel.each(function(i,v){ // loop through selected options
               var $index = $(v).index(); // get index of selected option
               $('select').not($(this).parent()).each(function(){  // loop through other select - not current one       
                   if($index != 0){ // not default index
                       $(this).find('option').eq($index).hide(); // hide selected option in other dropdowns
                   }
               });
           });    
        }).change(); // <-- trigger change right away
    });
    

    http://jsfiddle.net/VE7jA/

    0 讨论(0)
  • 2021-01-23 13:23

    Hiding option elements is not always supported. A more idiomatic approach would be to disable it.

    obj.prop("disabled", true);
    

    Or simplify it like this.

    $(".selectbox option:selected").prop("disabled", true);
    

    Or this.

    $(".selectbox").each(function() { 
         this.options[this.selectedIndex].disabled = true; 
    });
    
    0 讨论(0)
  • 2021-01-23 13:27
    $('.selectboxes option:selected').find("option").hide();
    

    You are trying to find('option') inside option.. Try this

    $('.selectboxes option:selected').hide(); 
    

    You can also remove the element once and for all if you are using it again..

    $('.selectboxes option:selected').remove();
    

    To remove a option based on value you can try

    $('.selectboxes option[value="0"]').remove() ; // Removes option with value 0
    
    0 讨论(0)
  • 2021-01-23 13:33

    As it's been said, you're trying to find an option within an option, so you'll have to get rid of the .find call.

    Apart from that, hiding <option> elements do not work cross-browser, so you'll have to remove the options instead, and add them back when necessary. There are several ways to manage that, all involving storing the full list of options in a variable (as an array, an object, or even HTML string).

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