how to tell is user selected the first index in a combobox in javascript
i have this code:
$('#categories').change(function() {
var myCars = new Array("Saab", "Volvo", "BMW");
addRowToTable(this.value, myCars);
$('#lis开发者_StackOverflow社区tings').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 . . ."
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.
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
}
If the user is to select a single value only:
- Add a distinct 'invalid' value to the first item
- 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();
});
精彩评论