In the following code when I change the selection, there will be an alert. I am trying to make the function like when I click on the option then it will show an alert.
$(document).ready(function() {
$("#x").change(function() {
alert("Haha");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="x">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
In the below code there is no effect when I click on the options already selected options. for example a is selected then i click a is no effect.
$(document).ready(function() {
$("#x").on("option", "click", function() {
alert("Haha");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="x">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
because i want to trigger event while i re-clicking the selected option.
click selection box->drop menu->click selected option->trigger event
Can anyone help me?
"click selection box->drop menu->click selected option->trigger event"
First of all do not use alert(), it prompts for an extra click you really don't need to waste your time on. Use console.log().
The following demo:
click event to select#x:$('#x').on('click',...
focus event on every even click✱:✱ if (cnt % 2 === 0) { $(this).trigger('focus');}
select#x is also delegated to the focus event and will call optionTrigger():$('#x').on('focus', optionTrigger);
function optionTrigger() will log the selected <option> index and text:✱ if (cnt < 2) {...
...$(this).trigger('blur'); }
var idx = $(this)[0].selectedIndex;
var txt = $(this).find('option').eq(idx).text();
var cnt = 1;
$("#x").on("click", function(e) {
if (cnt % 2 === 0) {
$(this).trigger('focus');
}
cnt++;
});
$('#x').on('focus', optionTrigger);
function optionTrigger(e) {
if (cnt < 2) {
$(this).trigger('blur');
} else {
var idx = $(this)[0].selectedIndex;
var txt = $(this).find('option').eq(idx).text();
console.log(idx + ': ' + txt);
}
}
<select id="x">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With