Reputation: 437
I have a function that I want to call when an item in a drop down (id=ddlTest) list besides the first one is clicked. Below is the code I have. It works fine in IE but not Chrome, any idea why?
jQuery('#ddlTest').on('click', 'option:gt(0)', function() {
alert('test'); //never runs
});
Update: I got the below working but it can easily be broken if the user clicks the DDL and then off of it
var ddlCounter = 1;
jQuery(function () {
jQuery("#ddlTest").on('click', function () {
if (ddlCounter % 2 === 0) {
if (this.selectedIndex > 0) {
showHideFunction();
}
}
ddlCounter += 1;
});
});
Upvotes: 0
Views: 1948
Reputation: 3750
Using Javascript's selectedIndex property will be better and faster
$("#ddlTest").on('change', function() {
if (this.selectedIndex > 0) {
alert("Greater than zero");
} else {
alert("Zero");
}
});
check it out here: https://plnkr.co/edit/2dZp5ZGA8A4l65wt5u3k?p=preview
Upvotes: 0
Reputation: 337560
You cannot reliably add a click event on a specific option
element within a select
.
A better alternative would be to put a change
event handler on a select
and then check the index()
of the chosen option:
$('#ddlTest').on('change', 'select', function() {
var index = $(this).find('option:selected').index();
if (index == 0) {
console.log('You chose the first option');
} else {
console.log('You did not choose the first option');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ddlTest">
<select>
<option>Please select</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
Upvotes: 1