Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

jQuery chained/filtered dropdown doesn't work for all selections

$
0
0

Keep in mind, I don't want to use the Chained.JS or any Django plugins, I've had nothing but issues with them and I've been attempting this for a long time. I really wanted to attempt this myself using jQuery as I feel it shouldn't be too difficult, and previous plugins I had (django smart selects, chained.js) weren't playing well with the other features on my site (and specifically the page this is on).

Here it goes:

$(document).ready(function(){
    $("#id_carmake").change(function(){
    $("#id_carmodel option").hide();
    var carbrand = $("#id_carmake option:selected").text();
    $("#id_carmodel option:contains('"+ carbrand +"')").show().filter(function(i){
        return $(this).text() === carbrand;}).prop("selected", true);
    });
});

This is the code I'm using to make my second dropdown selection based upon the first selection (car make, car model). I believe this is self-explanatory. It actually works! 90% of the time. Most "makes" will populate the second dropdown with their "models".

The second dropdown includes the make name ("Ford F150", "Toyota Prius", etc) so I was able to filter by included text. I am wondering if something is wrong with my code, I am not a JavaScript or jQuery expert, but want to know what I'm doing wrong so I can improve and move past this issue - any help would be appreciated.

I'm using jQuery 3.4.1.

Here's a shortened version of the HTML dropdown if it helps:

<select name="carmake" class="select form-control" required="" id="id_carmake"> 
  <option value="" selected="">---------</option> 
  <option value="1">Acura</option> <option value="2">Alfa Romeo</option> 
  <option value="3">AMC</option> 
  <option value="4">Aston Martin</option> 
</select>

<select name="carmodel" class="select form-control" required="" id="id_carmodel"> 
  <option value="" selected="" style="">---------</option> 
  <option value="1" style="display: none;">Acura 2.2CL</option> 
  <option value="2" style="display: none;">Acura 2.3CL</option> 
  <option value="3" style="display: none;">Acura 3.0CL</option> 
</select>

Viewing all articles
Browse latest Browse all 138134

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>