Avatar of Camillia
Camillia
Flag for United States of America

asked on 

Change this jQuery to look for a word

This is related question that leakme and Alexander helped me with here. I don't have a QA server to upload this to.
If user selects "Canada", only states from Canada should be displayed in States ddl. If "US" is selected, only US states should show.

https://www.experts-exchange.com/questions/28562594/How-can-I-hide-some-options-in-a-dropdown.html

This works but I finally was able to get the dropdown working by adding a custom attribute.
Now, the ddl looks like this. It has "data-countrycode". It doesn't have "value=118-126".

   <select id="StateId">
                           
                                <option value="118" data-countrycode="126">
                                    Alabama
                                </option>
                                <option value="169" data-countrycode="25">
                                    Alberta
                                </option>
                     
                        </select>

How can I change this jquery to not looking for "dash"...but look for "data-countrycode". In the code below, i replaced the "-" with "data-countrycode". Switched the country but it only displayed one state.

I tried this but didnt work
reverseLogic[i].value.indexOf("data-countrycode=" + "''"+ val +"''")

Open in new window


 jQuery(function($) {
        var reverseLogic = [];
        $("#StateId option:gt(0)").each(function(i, v) {
            reverseLogic.push({ value: $(this).val(), text: $(this).text() });
        });
        $("#CountryId").change(function() {
            var putAllBack = $(this).prop("selectedIndex") == 0;
            var val = $(this).val();
            $("#StateId option:gt(0)").remove();
            for (var i = 0; i < reverseLogic.length; i++) {
                if (putAllBack || reverseLogic[i].value.indexOf("-" + val) > 0) {
                    $("#StateId").append("<option value='" + reverseLogic[i].value + "'>" + reverseLogic[i].text + "</option>");
                }
            }
        }).change();
    });

Open in new window


This is how the Country ddl looks like

<select data-val="true"  id="CountryId" name="CountryId"><option value="Selects items">Country*</option>
<option value="25">Canada</option>
<option value="126">United States</option>
</select>

Open in new window

jQueryJavaScriptASP.NET

Avatar of undefined
Last Comment
Camillia

8/22/2022 - Mon