views:

172

answers:

3

i have this code:

    $('#categories').change(function() {
            var myCars = new Array("Saab", "Volvo", "BMW");
            addRowToTable(this.value, myCars);
            $('#listings').hide();
        });

but i dont want it to call the addRowToTable method if the user selects the first item because the first element says "Please select an item . . ."

A: 

Assuming "categories" is the ID of your dropdown list you can do it like this:

$('#categories option:selected')

That should return all of the selected options in the dropdownlist (of which there will be either one or none).

Getting the value of the selected item can be done like so:

$('#categories option:selected').val()

To see if the selected item and the first item are the same just a quick comparison will do:

if ($('#categories option:selected').val() == $('#categories option:first').val())
{
//do something here
}
Sonny Boy
A: 

If the user is to select a single value only:

  1. Add a distinct 'invalid' value to the first item
  2. Check for that value and act accordingly

Assuming the invalid value is zero and all other choices have integer values:

$('#categories option:selected').change(function() {
    if ($(this).val() === 0) {
        return;
    }

    var myCars = new Array("Saab", "Volvo", "BMW");
    addRowToTable(this.value, myCars);
    $('#listings').hide();
});
Jon Cram
+1  A: 

Well, I'd think that using the selectedIndex property of your drop-down list should be enough:

$('#categories').change(function() {
    if(this.selectedIndex!=0) {
        var myCars = new Array("Saab", "Volvo", "BMW");
        addRowToTable(this.value, myCars);
        $('#listings').hide();
    }
});

You could, of course, get creative with jQuery selectors, but if your present need is just skipping the first item, I think this is the simplest possible solution.

TataBlack
I'd suggest testing for `this.selectedIndex > 0`, as `selectedIndex` may report `-1` if even the first item has never been selected. Better than `selectedIndex`, hows about just `if(this.value)`?
Crescent Fresh