Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the event of first option selected with jquery?

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 () {
      ...
})
like image 206
toyaji Avatar asked Jan 22 '26 05:01

toyaji


2 Answers

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.

like image 50
Dawid Zbiński Avatar answered Jan 24 '26 18:01

Dawid Zbiński


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>
like image 25
MrCode Avatar answered Jan 24 '26 17:01

MrCode