jQuery filtering select options does not work in S

2020-04-30 03:28发布

I have a form with some dropdowns, and the first selected dropdown will serve to filter the second dropdown's choices (to limit them). The following code works just fine in FF and Chrome but will not work in Safari (version 11.1.2 at least):

if(~jQuery(this).attr('id').indexOf('5b0ad35592224') && ~jQuery(this).attr('id').indexOf(jQuery(this).closest('tr').attr('data-id'))) {
        var vallie = jQuery(this).val();
        var sub = jQuery('[id*="'+jQuery(this).closest('tr').attr('data-id')+'-field_5b0ad39f92225"]');
        console.log(sub);
        jQuery('option', sub).filter(function(){
            if (~jQuery(this).val().indexOf(vallie) || jQuery(this).val() === 'Choisir') {
                jQuery(this).show();
            } else {
                jQuery(this).hide();
            }
        });
      jQuery(sub).val('Choisir');  
    };

The odd thing is when I console log the values returned for vallie or sub or jQuery(this).val().indexOf(vallie) they are the same in all browsers. I am stumped as to why Safari does not filter the options in the second dropdown (it just shows all the options)

2条回答
叼着烟拽天下
2楼-- · 2020-04-30 03:36

Thanks to @charlietfl for alerting me to the fact that hiding options is not universally supported. Here is the solution I ended up going with:

  1. I separated my options into separate js objects
  2. I then check the value from the first dropdown, and use that to get the correct menu object
  3. I then empty the existing (full) menu, and then append the options from the appropriate object.

Here is the actual code:

if(~jQuery(this).attr('id').indexOf('5b0ad35592224') && ~jQuery(this).attr('id').indexOf(jQuery(this).closest('tr').attr('data-id'))) {
  var vallie = jQuery(this).val();
  var thismenu = menu_portes; // set default menu object
  if (vallie === 'Tiroir') {thismenu = menu_tiroirs } else if (vallie === 'Côté') {thismenu = menu_cotes }
  var $sub = jQuery('[id*="'+jQuery(this).closest('tr').attr('data-id')+'-field_5b0ad39f92225"]');

  $sub.empty(); // remove old options
  $sub.append(jQuery('<option>', { value: 'Choisir', text: 'Choisir'})); // add Choisir at top
  jQuery.each(thismenu, function(key,value) { // loop through my object options
    $sub.append(jQuery("<option></option>").attr("value", key).text(value)); //append options from my menu object
  });
  jQuery($sub).val('Choisir'); // set menu to Choisir 
  };
查看更多
Root(大扎)
3楼-- · 2020-04-30 03:41

If you are going to use .filter, you should be return a boolean indicating whether or not to include the current item instead of using .show() and .hide() documentation

Otherwise, use .each or .map

查看更多
登录 后发表回答