March 28, 2012

Jquery form onchange select values changing

Question by Malyo

I’m looking for best solution to this problem. I have a simple shop logical problem. There are 2 select elements, size and color. I want to make them dependent, on data (now it’s example data, but later it’s gonna be from database) – size will decide which color options will be visible for customer (hiding not necessary ones).

First problem is that when i make change event, and i wanna hide the default shown element on document ready, it’s still visible (i’d have to change color to different than open dropdown again and it won’t be visible then).

Second is that i’m looking for most flexible solution, since i have doubts about mine. Here’s the code:

       var rozmiar = new Array("S", "M", "L", "XL", "XXL");
   var kolor = new Array("Czerwony", "Niebieski", "Zielony", "Biały", "Czarny");
   var opcje = new Array( rozmiar, kolor);

        $(document).ready(function(){
        $('.form1').change(function(){
                $('.form2 option').show();

                var selectSelector = function(z){
                    selectSelector = $('select.form2 option[value='+kolor[z]+']').hide();
                };

                wybranyRozmiar = $(this).val();
                    if(wybranyRozmiar == rozmiar[0]){
                        selectSelector(0);
                    }
                    if(wybranyRozmiar == rozmiar[1]){
                        selectSelector(1);
                    }
                    if(wybranyRozmiar == rozmiar[2]){
                        selectSelector(2);
                    }
                    if(wybranyRozmiar == rozmiar[3]){
                        selectSelector(3);
                    }
                    if(wybranyRozmiar == rozmiar[4]){
                        selectSelector(4);
                    }
            });
        });

Answer by Starx

I am answering the only part I understand.

Instead of using multiple if statements you can use switch

switch(selectsize) {
   case rozmiar[1]:
       $('select.form2 option[value='+color[2]+']').hide();
       break;
   //case <another>"
       //break;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!