Home » Jquery » jquery – select box option remove() works but hide() did not

jquery – select box option remove() works but hide() did not

Posted by: admin February 22, 2020 Leave a comment

Questions:

I would like to show and hide select box options depending on the value of an input field. Strangely enough, this only works with $('thisOption'). Remove () but NOT with:

$('thisOption').hide() 
// or:
$('thisOption').css('visibility', 'hidden')
$('#Selectkk').Load('JSON / kk_select_box.php')
// callback after select box is ready
function() {
  var i, filter,
    $ input = $('# ort_kk'),
    $ options = $('# select_kk').find('option')
  $ Input.keyup(function() {
    filter = $ input.val()
    $ Options.each(function() {
      var option_text = $(this).text();
      var pos = option_text.search(filter);
      if (pos == -1) {
        $(This).remove();
      }
    })
  });
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='input-group'>
  <input name='ort_kk' id='ort_kk' value=''>
</div>
<div id='selectkk'> </div>

I don’t want to remove the options. If the input field is corrected, all options for filtering must still be there. So roughly:

if (pos == -1) {
  $(This).hide(); 
} else {
  $(This).show();
}

I hope I was able to describe the problem clearly and hope for your help.
Thank you very much
Thomas

How to&Answer:

Sorry!! Once again:
Yes, code works at all.

$('#selectkk').load('JSON/kk_select_box.php?' + $.param({
          kk: encodeURIComponent(''),
         plz: encodeURIComponent(''),
         ort: encodeURIComponent(''),        
     }),
                // callback function after selectbox has load 
                function(){
                    var i, filter,
                    $input = $('#ort_kk'),          
                    $options =$('#select_kk').find('option')                    
                    $input.keyup(function(){
                            filter = $input.val()
                            $options.each(function(){
                                var option_text=$(this).text();
                                var pos = option_text.search(filter);
                                if( pos == -1 ){ 
                                    $(this).remove(); }
                                })

                    });

                }                 
           );

But nevertheless, this won’t work:

...
    if (pos == -1) {
      $(this).hide(); 
    } else {
      $(this).show();
    }
...