81

given:

<select id="mySelect">
  <option>..</option>
  ...
</select>

Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).

1

9 Answers 9

93

You want the 'change' event handler, instead of 'click'.

$('#mySelect').change(function(){ 
    var value = $(this).val();
});
Sign up to request clarification or add additional context in comments.

7 Comments

what if they choose the same option? the change event is not triggered
@haz0rd you will only be able to detect that with the click event, of which you will get 2. 1 when you first click the select, and 1 when you select the already selected option
Please note click events do not currently get generated in Chrome at all for <option> elements.
@GoneCoding Is there any way around the click not firing in Chrome?
Its not what he asked for or what he "wants". He asked for an event that triggers on a click on one of the options. Your answer is a workaround that wont't trigger when click on default or same option
|
44

$('#mySelect').on('change', function() {
  var value = $(this).val();
  alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
  <option value='4'>4</option>
  <option value='5'>5</option>
  <option value='6'>6</option>
  <option value='7'>7</option>
  <option value='8'>8</option>
</select>


EXAMPLE

1 Comment

var value = this.value also works perfectly for this. No need to wrap in jquery selector
5

you can attach a focus event to select

$('#select_id').focus(function() {
    console.log('Handler for .focus() called.');
});

Comments

0

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

Comments

0

You can also try this to get previous value of select and the clicked value.

HTML

<select name="status">
    <option value="confirmed">confirmed</option>
    <option value="packed">packed</option>
    <option value="shiped">shiped</option>
    <option value="delivered">delivered</option>
</select>

script


    var previous;

    $("select[name=status]").focus(function () {
        previous = this.value;
    }).change(function() {
        var next = $(this).val()
        
        alert("previous: "+previous+ " and Next: "+ next)
        
        previous = this.value;
    });


Comments

0
    <select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
    <option value = 0>All</option>
    <option value = 1>Diseases</option>
    <option value = 2>Drugs</option>
    <option value = 3>Procedures</option>
    </select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);

Comments

-1

What I have done in this situation is that I put in the option elements OnClick event like this:

<option onClick="something();">Option Name</option>

Then just create a script function like this:

function something(){
    alert("Hello"); 
    }

UPDATE: Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm

3 Comments

This does not currently work with Chrome so should be avoided: jsfiddle.net/TrueBlueAussie/jd3bamtr/1
p.s your code lacks the javascript code so....next time at least make sure you have everything implemented to someones suggestions and checked via "Chromes" debugger that its not working and why !!before warning other users!! that its not working and downvoting ;)
The only Javascript required for that test was inline. If you actually bother to put your <option> inside a <select>, to make it valid HTML, you will see your code does not work on Chrome: jsfiddle.net/TrueBlueAussie/j6fkLjc8 The downvote is correct. This code should not be used until Chrome fix that problem :P
-1

What you are looking for is onFocus like this:

$("#mySelect").on("focus", function(){});

This fires when select is clicked before any option was chosen.

Comments

-2

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

11 Comments

@TrueBlueAussie just tested your fiddle in FF and IE and it works as expected
@TrueBlueAussie and even in the old good Opera 12 it does work!
@TrueBlueAussie I understand, you've tested it just in chrome and I tested it everywhere else besides chrome. Otherwise you should write "it doesn't work in crome" instead of "Click events are eaten by the drop down" which is obviously incorrect. See my update
That is impractical. If it does not work in one of the most popular browsers then it is not a practical solution. It is not my responsibility to test your answer in all browsers. That would be yours :)
Previous ambiguous comment removed. Just to clarify for the pedantic: This solution does not work for Chrome as of this time of writing: jsfiddle.net/TrueBlueAussie/jd3bamtr
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.