Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery simulate click event on select option

I have a select menu that triggers an AJAX request once one of the options has been clicked. I need to trigger a click event on the relevant option from a link. So I have code similar to the below, and although it changes the value of the select, it doesn't simulate a click:

$('#click').click(function(){
    var value = $(this).attr("rel");
    $('#select').val(value);
    return false;
});
<select id="select" name="select">
    <option>Select...</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
    
<a href="#" rel="1" id="click">Click for option 1</a>
like image 253
Stuart Taylor-Jones Avatar asked Mar 21 '13 14:03

Stuart Taylor-Jones


2 Answers

Triggering a click event on the option will not work. Here is a snippet that does:

    $('#click').on('click', function(){
        var value = $(this).attr('rel'); //get the value
        value++; //increment value for the nth-child selector to work

        $('#select')
          .find('option:nth-child(' + value + ')')
          .prop('selected',true)
          .trigger('change'); //trigger a change instead of click

        return false;
    });

I have setup a fiddle here showing the same. This should work.

Instead of using a click you can trigger the change event and achieve the same effect.

like image 104
larrydalmeida Avatar answered Nov 07 '22 10:11

larrydalmeida


$('#click').click(function(){
    var value = $(this).attr("rel");
    $('#select')
        .val(value)
        .trigger('click');
    return false;
});

Merely setting the value of a <select> does not trigger the click event of that element; it must be called directly.

like image 42
Brad M Avatar answered Nov 07 '22 12:11

Brad M