This question comes to my attention as this is pretty basic stuff but no one actually dig into it further. OP has been using change()
, but when you reselect the current selected option nothing is fired!
I tried click()
, but it's firing before you can even choose an option.
With blur()
, after you're done selecting nothing is fired because the the select element is still being focused, so you need to focus out like clicking outside for it to execute.
So I just suggested OP to switch to a radio
type input then handle execution with click()
event. That way you can still reselect already marked radio button.
But then I noticed that you just need to get the second click on <select>
element because the first click opens the drop down list of options the second click returns the value of your selected option. So I came up with this:
$('select').click(function(){
var $this = $(this);
if ($this.hasClass('open')) {
alert($this.val());
$this.removeClass('open');
}else {
$this.addClass('open');
}
});
But now the problem is when you first click on <select>
the drop down is being showned and we've also added the class 'open'
. Then clicking elsewhere (without selecting an option) the drop down is hidden so when you click back on <select>
the event is fired before you can even select an option.
So I added this code to fix that:
$(document).click(function(e){
var $select = $('select');
if (!$select.is(e.target)){
$select.removeClass('open'); //reset the steps by removing open
}
});
You can test it out in this jsfiddle. Cheers!
I think when <select>
loses its focus is also a concern. So I added blur()
event. See this update jsfiddle
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…