简体   繁体   中英

Jquery once two options have been selected from select drop down list run code

I have 2 select drop down menus. I want to to add a class once a option has been selected from both menus.

    $('#size').change(function(){ 
        if ($(this).val() > 0 )  {
              $('#pizza').addClass('pizzaImage');
         }  

    });

    $('#crust').change(function(){ 
        if ($(this).val() > 0 ) {
              $('#pizza').addClass('pizzaImage');
         }  


    });

This is my code so far, it works when I select an option from one. Basically I want to put these together I just don't know the syntax to do so. I also tried this but no results.

var size = $('#size')
var crust = $('#crust')

function image () {
  if ((crust).val > 0 && (size).val > 0) {
    $('#pizza').addClass('pizzaImage');
  }
}
var $selects = $('#size, #crust');
$selects.change(function(){
   var bothSelected = this.value && $selects.not(this).val();
   $("#pizza").toggleClass("pizzaImage", bothSelected);
});

I would start by adding a common class between the two, to make it easier to bind the function to both select elements at the same time. Maybe something like pizzaOptions. Then, you could do something like this:

$(".pizzaOptions").on("change", function(){
    var sizeSelected = $("#size").val() !== ""; 
    var crustSelected = $("#crust").val() !== ""; 

   if(sizeSelected && crustSelected){
        $('#pizza').addClass('pizzaImage');
   }
}); 

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