views:

37

answers:

2

Dear ALL, I am trying to do soemthing quite straightforward but can't get my head around the syntax.

I have a dropdown list. The OPTIONs have two types of classes. If an OPTION with class 'less_than_3' is chosen we see an alert. And if an OPTION with class 'greater'- we see a different alert.

Heres my attempt: (please note I originally had a working version by attaching the click handler directly to the OPTION element. but this only worked in Firefox so I changed my approach.

$('#time_at_address').change(function() {
    if ( $(this).children('.less_than_3:selected') )  {
        alert('less than 3!');
    }
    if ( $(this).children('.greater_than_3:selected') )  {
        alert('greater than 3!');
        }
    });
A: 

I am not sure whether an empty array evaluates to false in JS. So to be sure you can use:

$(this).children('.less_than_3:selected').length > 0

Syntax looks fine. I assume your actual problem is that the alert box is showing up.

Felix Kling
Thanks Felix. But that '.length > 0' is throwing an error.Just to clarfiy - all I am trying to do is that when the user chooses a certain option from the list, a certain DIV is displayed. (and if they choose a different option, a different DIV is displayed)>i just used alerts to simplify things. im not even sure if im supposed to be using :selected (when i look in Firebug the attribute isn't even there)
swisstony
A: 

I managed to solve4 this using a different approach. By using val() isntead of filtering by class name.

Thus..

    $('#time_at_address').change(function() {
            if ( $(this).val() == 'less than 1' ) {
                    $('#address_less_than').show();
            }
            else if ( $(this).val() == '1 year' ) {
                    $('#address_less_than').show();
            }
            else if ( $(this).val() == '2 years' ) {
                    $('#address_less_than').show();
            }
            else {
                $('#address_less_than').hide();
            }
    });

But can anyone please tell me... is it not possible to chain those first statements (the IF and the two ELSE IFs) together? (since they return the same result.)

I tried using the two verticle pipe characters, but it didn't work

swisstony
try myval = $(this).val();if ((myval == 'less than 1' ) || (myval == '1 year') || (myval == '2 years' )){ $('#address_less_than').show(); } else {$('#address_less_than').hide(); }
Mark Schultheiss
Yes, it does! thanks for that Mark. Its reduced my code a little. Any idea why it needs to be in a variable for || to work?
swisstony