I need a event trigger when select option selected. I use below code using ".change" But I met a problem when first option selected. If user select first option, then it means there is no change, right? So, below code doesn't work...
How can I get the right event trigger beside ".change" ?
my.js
$(document).ready(function () {
$("#select-choice-2").change(function () {
...
})
This would run a function every time the user changes the option (except the situation when selected option is selected again - it doesn't trigger any change event, as there's no change in the input's value):
$(".myselect").change(function(){
if ($(this).val() == 1) {
console.log("First option selected");
}
});
When you expect user to submit the form without changing anything (e.g. when the 1st option is selected by default) you can use the simple if statement inside submit event handler:
$(".myform").submit(function(){
if($(".myselect").val() == 1) {
// do stuff
}
});
This will probably help, but as @MrCode has pointed out, it's normally handled by putting the <option val="" disabled selected>Please, select something</option>, so the user needs to click and change the value. This will trigger the change event on select input element, so you can handle it just once.
This is usually handled by putting a "Please Select" option as the first option, which forces the user to change the option and your event will be triggered.
<select id="#select-choice-2">
<option value="">Please Select</option>
<option>First</option>
<option>Second</option>
</select>
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