Elyor Elyor - 14 days ago 5
Javascript Question

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

Answer

Well it works even if you check one condition i.e. 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>

Comments