The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown.

While this feature works perfectly in Chrome, it seems to be malfunctioning in Safari and on iPhones. After researching online, I discovered that Safari does not allow hiding options, which explains the problem. I attempted to come up with a solution, but it only partially resolves the issue. How can I adjust the code to make sure it works consistently across all browsers?

// get first dropdown and bind change event handler
$('#p-city').change(function() {
  // get optios of second dropdown and cache it
  var $options = $('#p-nhb')
    // update the dropdown value if necessary
    .val('')
    // get options
    .find('option')
    // show all of them initially
    .show();

  // IF SAFARI
  if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
    var $options = $('#p-nhb').val('').find('option').append();
  }

  // check current value is not 0
  if (this.value != '0')
    $options
    // filter out options which don't correspond to the selected option
    .not('[data-val="' + this.value + '"],[data-val=""]')
    // hide those options
    .hide();

  // IF SAFARI
  if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
    $options.not('[data-val="' + this.value + '"],[data-val=""]').detach();
  }
})
$('#p-city').trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<select name="property_city" id="p-city">
  <option class="button" value="new-york-city" selected>New York City</option>
  <option class="button" value="">All</option>
  <option class="button" value="dallas-tx">Dallas, TX</option>
  <option class="button" value="las-vegas">Las Vegas, NV</option>
  <option class="button" value="los-angeles">Los Angeles, CA</option>
  <option class="button" value="miami">Miami, FL</option>
  <option class="button" value="new-york-city">New York City, NY</option>
  <option class="button" value="san-francisco">San Francisco, CA</option>
  <option class="button" value="seattle-wa">Seattle, WA</option>
</select>
</p>

<p>
<select name="property_nhb[]" id="p-nhb" multiple>
  <option class="button">All</option>
  <option data-val="los-angeles" value="beverly-hills" >Beverly Hills</option>
  <option data-val="los-angeles" value="santa-monica" >Santa Monica</option>
  <option data-val="miami" value="hialea" >Hialea</option>
  <option data-val="miami" value="little-havana">Little Havana</option>
  <option data-val="miami" value="north-miami">North Miami</option>
  <option data-val="miami" value="south-beach">South Beach</option>
  <option data-val="new-york-city" value="chelsea">Chelsea</option>
  <option data-val="new-york-city" value="harlem">Harlem</option>
  <option data-val="new-york-city" value="noho">NoHo</option>
  <option data-val="new-york-city" value="soho">SoHo</option>
</select>
</p>

UPDATE

I've noticed that another function of mine also doesn't work in Safari --

$("#search-tabs").on('click','li', function(e) {
  $('.searchbox').hide().eq($(this).index()).show();
});

Therefore, it seems that ".hide" and ".show" do not function as expected in Safari. Is there a simple alternative without needing to rewrite a significant amount of code?

UPDATE 2

The CSS property `.css('display', 'none');` successfully replaces `.hide`, but it does not apply to the select options-

  .css('display', 'none');

UPDATE 3

This snippet shows how the drop downs were rendered initially --

<select name="property_city" class="form-control" id="p-city">
<?php
$terms = get_terms( "city-type", array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => 0 ) );
 $count = count($terms);
 if ( $count > 0  ){
echo "<option class='button' value='new-york-city'>New York City</option>";
echo "<option class='button' value=''>All</option>";
     foreach ( $terms as $term ) {
         echo "<option class='button' value='" . $term->slug . "'>" . $term->name . "</option>";
     }
 }
?>
  </select>

<label>Neighborhood</label>
<?php $taxonomyName = "city-type"; 
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );   
echo "<select name='property_nhb[]' class='form-control' id='p-nhb' style='border-left: 1px solid #000 !important;' multiple>";
echo "<option class='button'>All</option>";
foreach ( $parent_terms as $pterm ) {
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {
        echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "'>" . $term->name . "</option>"; 
    }
}
echo "</select>"; 
?>

Answer №1

One solution that is guaranteed to work on all browsers is to create a cached list of options and then append it to the second select box.

var select_clone = $('#p-nhb option');
$('#p-city')
  .change(function() {
    $('#p-nhb').html(select_clone.filter('[data-val="' + this.value + '"]'));
  })
  .change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<select name="property_city" id="p-city">
  <option class="button" value="new-york-city" selected>New York City</option>
  <option class="button" value="">All</option>
  <option class="button" value="dallas-tx">Dallas, TX</option>
  <option class="button" value="las-vegas">Las Vegas, NV</option>
  <option class="button" value="los-angeles">Los Angeles, CA</option>
  <option class="button" value="miami">Miami, FL</option>
  <option class="button" value="new-york-city">New York City, NY</option>
  <option class="button" value="san-francisco">San Francisco, CA</option>
  <option class="button" value="seattle-wa">Seattle, WA</option>
</select>
</p>

<p>
<select name="property_nhb[]" id="p-nhb" multiple>
  <option class="button">All</option>
  <option data-val="los-angeles" value="beverly-hills" >Beverly Hills</option>
  <option data-val="los-angeles" value="santa-monica" >Santa Monica</option>
  <option data-val="miami" value="hialea" >Hialea</option>
  <option data-val="miami" value="little-havana">Little Havana</option>
  <option data-val="miami" value="north-miami">North Miami</option>
  <option data-val="miami" value="south-beach">South Beach</option>
  <option data-val="new-york-city" value="chelsea">Chelsea</option>
  <option data-val="new-york-city" value="harlem">Harlem</option>
  <option data-val="new-york-city" value="noho">NoHo</option>
  <option data-val="new-york-city" value="soho">SoHo</option>
</select>
</p>

An alternative approach involves using a hidden select element to avoid the issue of duplicate lists:

var select_clone = $('<select>')
  .html($('#p-nhb option'))
  .hide()
  .insertAfter('#p-nhb');

$('#p-city')
  .change(function() {
    $('#p-nhb').html(select_clone.find('[data-val="' + this.value + '"]').clone());
  })
  .change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<select name="property_city" id="p-city">
  <option class="button" value="new-york-city" selected>New York City</option>
  <option class="button" value="">All</option>
  <option class="button" value="dallas-tx">Dallas, TX</option>
  <option class="button" value="las-vegas">Las Vegas, NV</option>
  <option class="button" value="los-angeles">Los Angeles, CA</option>
  <option class="button" value="miami">Miami, FL</option>
  <option class="button" value="new-york-city">New York City, NY</option>
  <option class="button" value="san-francisco">San Francisco, CA</option>
  <option class="button" value="seattle-wa">Seattle, WA</option>
</select>
</p>

<p>
<select name="property_nhb[]" id="p-nhb" multiple>
  <option class="button">All</option>
  <option data-val="los-angeles" value="beverly-hills" >Beverly Hills</option>
  <option data-val="los-angeles" value="santa-monica" >Santa Monica</option>
  <option data-val="miami" value="hialea" >Hialea</option>
  <option data-val="miami" value="little-havana">Little Havana</option>
  <option data-val="miami" value="north-miami">North Miami</option>
  <option data-val="miami" value="south-beach">South Beach</option>
  <option data-val="new-york-city" value="chelsea">Chelsea</option>
  <option data-val="new-york-city" value="harlem">Harlem</option>
  <option data-val="new-york-city" value="noho">NoHo</option>
  <option data-val="new-york-city" value="soho">SoHo</option>
</select>
</p>

Answer №2

I prefer using a method where values are updated from a hidden select and displayed based on certain criteria. This approach ensures compatibility across different browsers.

<p>
<select name="property_city" id="p-city">
  <option class="button" value="new-york-city" selected>New York City</option>
  <option class="button" value="">All</option>
  <option class="button" value="dallas-tx">Dallas, TX</option>
  <option class="button" value="las-vegas">Las Vegas, NV</option>
  <option class="button" value="los-angeles">Los Angeles, CA</option>
  <option class="button" value="miami">Miami, FL</option>
  <option class="button" value="new-york-city">New York City, NY</option>
  <option class="button" value="san-francisco">San Francisco, CA</option>
  <option class="button" value="seattle-wa">Seattle, WA</option>
</select>
</p>

<p>
<select name="property_nhb[]" id="p-nhb" multiple>
</select>
<select name="property_nhb[]" id="p-nhb-back" style="display:none" multiple>
  <option class="button">All</option>
  <option data-val="los-angeles" value="beverly-hills" >Beverly Hills</option>
  <option data-val="los-angeles" value="santa-monica" >Santa Monica</option>
  <option data-val="miami" value="hialea" >Hialea</option>
  <option data-val="miami" value="little-havana">Little Havana</option>
  <option data-val="miami" value="north-miami">North Miami</option>
  <option data-val="miami" value="south-beach">South Beach</option>
  <option data-val="new-york-city" value="chelsea">Chelsea</option>
  <option data-val="new-york-city" value="harlem">Harlem</option>
  <option data-val="new-york-city" value="noho">NoHo</option>
  <option data-val="new-york-city" value="soho">SoHo</option>
</select>
</p>

This can be accompanied by a simple JavaScript code:

// get first dropdown and bind change event handler
$('#p-city').change(function() {
  // get options of second dropdown and cache it
  var $options = $('#p-nhb')
    // update the dropdown value if necessary
    .val('')
    // get options
    .find('option')
    // show all options initially
    .remove();


    $("#p-nhb").append($('#p-nhb-back option[data-val="' + this.value + '"],[data-val=""]'));
})
$('#p-city').trigger('change');

This approach has worked well for me. Here is a jsfiddle link for reference:

https://jsfiddle.net/cckhgw5g/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why won't the value in jQuery attr() be updated?

Just joined this platform for the first time and can't seem to find a similar issue posted before.. :( I'm currently trying to catch up with jQuery and JavaScript. My problem is that I want to dynamically change the href attribute of an anchor e ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

Utilize Bootstrap to align two images in the same row and adjust their sizes accordingly

I am looking to display 2 images side by side on a single row, with the ability for them to resize accordingly when adjusting the page size without shifting to another row. Currently, as I decrease the page size, the second image (the black block in the d ...

Instructions on using $.post in jquery to sude uploaded file to a php file for processing

Is there a way to upload photos asynchronously using $.post without relying on .serializeArray()? I want to send a form, containing an upload file, to a PHP processing file. Any suggestions? HTML: <form action="upload1.php" method="post" id="usrform" ...

Wrap the text in Alphine using PHP

Currently, I am dealing with a situation where I have a string that needs to be wrapped using the Yii tag like Yii::t('app' , 'what_string'). The reason for this is because I require it to be translated per string on another page. Howev ...

What is the method for applying the action (hide) to every table cell that doesn't include a specific string in its ID?

I have a table with cells containing unique IDs such as "2012-01-01_841241" that include a date and a number. My goal is to filter the table to only display three specific numbers by sending a request and receiving those numbers. Is there a more efficien ...

Post-render for HTML linkage

Is there a method to execute customized code after Knockout has inserted the html into the DOM and completed rendering? This is required in order to bind a nested view model to dynamically generated html code. Perhaps like this: <div data-bind="html: ...

Using Material-UI to add a pseudo class '::before' with component class properties

I attempted to utilize a pseudo class for the mui-app-bar but did not have success. I've researched this issue on various platforms without finding a solution. Below is how my component is currently structured: const styles = (theme: Theme) => cre ...

Exploring the world with Algolia's search capabilities

I've been working on implementing geo search with Algolia for a web project. Here's the code snippet I have so far: var searchClient = algoliasearch(Algol_APP_ID, Algol_API_KEY); var itemIndex = searchClient.initIndex('item'); functio ...

Exploring the integration of mixins from .scss files within node_modules into our .tsx or .jsx files for enhanced styling

I am currently facing a challenge with importing a .scss file from one of the installed node_modules into my .tsx file. The scss file contains a mixin named @mixin make-embedded-control($className: embedded-control){.....} which has all the necessary css ...

Having trouble getting the on:dblclick event to trigger on a row within a list using S

I am currently using Sveltestrap and I am in need of a double click handler for a row: <ListGroupItem on:dblclick={handler(params)}> <Row> <Col><Icon name=........</Col> ... </Row> </ListGroupItem> Int ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

What is the best way to retrieve an item using a composite key?

const dynamoDB = new AWS.DynamoDB.DocumentClient(); var parameters: any = {}; parameters.TableName = 'StockDailyCandles'; var primarykey = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // sa ...

Leveraging the power of fullpage.js to activate Velocity.js/Blast.js animations

Referencing a solution shared on this forum: Velocity.js/Blast.js starting opacity at 0 I am currently working with Velocity.js and Blast.js to implement a basic word-by-word loading animation, commonly used. This setup also involves Cycle2. Additionally, ...

Using Angular 10 to make an HTTP POST request, with the goal of appending a string

Whenever I try to send a post request to an api endpoint, I keep encountering an error with status code 500. name: "HttpErrorResponse" ok: false status: 500 statusText: "Internal Server Error" Below is the code I am using: var selected ...

The antithesis of a feature that encapsulates a chosen area with a span

Hi everyone, I have a function that works as follows: define(function () { 'use strict'; var sel, range, span; return function () { span = document.createElement("span"); span.className = 'highlight'; if (window.ge ...

Continuous loop of Vue countdown timer

Hey there! I'm currently working on implementing a countdown timer, but I keep encountering a console error that says 'You may have an infinite update loop in a component render function.' It seems like something needs to be adjusted. expor ...

Is it possible for me to invoke an anonymous self-executing function from a separate scope?

I'm having an issue with calling the hello() function in ReactJS. When I try to call it, I receive an error message that says "Uncaught ReferenceError: hello is not defined". How can I go about resolving this error? This is a snippet from my index.ht ...

Update the Material-UI theme to a personalized design

I am currently using Material-UI in my React project. However, I'm facing some difficulties in applying a theme globally. Up until now, I have only managed to apply the theme to individual components like this: import { MuiThemeProvider, createMuiTh ...