简体   繁体   中英

append select option if value equal or selected in jquery

I have 2 select tags. second is depend on the first one. It is working if I check by only value, but I also need to check if is selected.

if(el.val() === "LOCATIONS" || el.is(' option:selected') ){
 $("#status option").remove();
 $("#status").append("<option value=''>All Packages</option><option value=''>KL</option>");
}

I'm trying to make depended select dropdown. if I remove el.is('option:selected') it appends the options based on the chosen option of 1st select. but it should also append the options if any option is selected on the first dropdown

here is jsfiddle

Well it works even if you check one condition ie the value of selected option. But to pass two conditions you have to use && operator and instead of el.is('option:selected') , you can change this to ("el:selected"); as below,

 $(document).ready(function() { var a = $("#source > option:selected").val(); if(a == "REGIONAL"){ $("#status option").remove(); $("#status").append("<option value=''>All Packages</option><option value='Airports'>Airports</option>"); } $("#source").change(function() { var el = $(this); if((el.val() === "AUDIENCES SEGMENT") && ('el:selected')) { $("#status option").remove(); $("#status").append("<option value=''>All Packages</option><option value='Youth'>Youth</option><option value='Working Adults'>Working Adults</option><option value='Family'>Family</option><option value='Travellers'>Travellers</option>"); } else if((el.val() === "REGIONAL") && ('el:selected')) { $("#status option").remove(); $("#status").append("<option value=''>All Packages</option><option value='Airports'>Airports</option>"); } else if((el.val() === "LOCATIONS") && ('el:selected')) { $("#status option").remove(); $("#status").append("<option value=''>All Packages</option><option value=''>KL</option>"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Source: <select id="source" name="source"> <option>All Types</option> <option value="AUDIENCES SEGMENT">AUDIENCES SEGMENT</option> <option selected value="REGIONAL">REGIONAL</option> <option value="LOCATIONS">LOCATIONS</option> </select> Status: <select id="status" name="status"> <option>All Packages</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM