I\'ve got a problem making a click
event on an HTML option
element work.
Even a simple console.log(\'hello!\');
won\'t work.
In my case following code works
$('#myItem').change(function(){
//do somthing
})
Sample example will show how to change dropdown values and color for the OPTION on click or change of select
HTML:
<select name="options">
<option value="1">Red</option>
<option value="2" selected="1">Green</option>
<option value="3">Blue</option>
</select>
jQuery:
$("select").on("click", function () {
debugger;
var sVal = $(this).val();
$(this).css("background-color", "red");
$(this).find("option").css("background", "white");
$(this).find('option:selected').css("background-color", "red");
$("input").val($(this).val());
});
Demo
because change not good enough for me and I didn't find a way to trigger the option click what I did is
$('#mySelect').click(function () {
if ($(this).attr('optionclick') == '1') {
$(this).attr('optionclick', '0');
}
else {
$(this).attr('optionclick', '1');
}
});
I would suggest you to use .on() instead of .bind().
$('#mySelect').on('change', function(){
var $this = $(this),
$value = $this.val();
alert($value);
});
jsFiddle
Check this js fiddle --
http://jsfiddle.net/4W826/
HTML
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
JQUERY
$('#mySelect').bind('click', function(){
alert('hi!');
});
Change from Click
to Change
You can bind using .on()
by giving <select>
id. In general, change
is the event called upon <select>
.
So, there is no need to mention option
while binding event.
$(document).on('change','#mySelect', function(){<br>
console.log('hi!');
});
OR
$('#mySelect').bind('change',function(){<br>
console.log('hi!');
});