0

This question comes off another question here: use jquery to select a dropdown option

I am following this example however, I don't understand the demonstration in the top answer

$('select>option:eq(3)').attr('selected', true);

http://www.jsfiddle.net/gaby/CWvwn/

None of the answers provide the code for the link so that a user can click it to change the drop down option. What would a link look like to use this script?

Community
  • 1
  • 1
user2509945
  • 63
  • 1
  • 9

4 Answers4

0

One possible option is to use nth-child pseudo-selector like this:

$('select::nth-child(2)').attr('selected', true);

Or, if the select is properly done, like this:

<select>
    <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>
</select>

You can select via the value attribute:

$('select>option[value=4]').attr('selected', true);

Since you will surely want to have more of the links, it's handy to define a function:

JS

function showOptWithValue(which) {
    $('select>option[value=' + which + ']').attr('selected', true);
}

Now, to bind this function to your link, you can either use onclick:

HTML

<a href="#" onClick="showOptWithValue(3); return false;">The Link</a>

Or assign the click handler with pure jquery:

HTML

<a href="#">The Link</a>

JS

$('a').on('click', function(){
    showOptWithValue(3);
    return false;
});

Here is the JSFiddle with some working example: http://jsfiddle.net/FY3tz/1/

rene
  • 41,474
  • 78
  • 114
  • 152
MightyPork
  • 18,270
  • 10
  • 79
  • 133
0

Here you go: DEMO

$('.link').click(function() {
   $('select>option:eq(3)').attr('selected', true);
});
Gintas K
  • 1,438
  • 3
  • 18
  • 38
  • Thanks, so does `$('.link').click(function() { $('select>option:eq(3)').attr('selected', true); });` need to be written out for every option in a drop down list? – user2509945 Aug 02 '13 at 15:08
  • it depends of what functionallity you want to accomplish :) – Gintas K Aug 02 '13 at 15:09
0
//html

<a id="myLink" href="#">My link</a>
<select>
   <option>1</option>
   <option>2</option>
   <option>3</option>
   <option>4</option>
   <option>5</option>
</select>

//js

$('#myLink').click(function() {
    $('select>option:eq(3)').attr('selected', true);
})
Manish Kumar
  • 15,269
  • 5
  • 18
  • 27
0
    <select>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>


    <a id="btn-change-option" data-option="2" href="#">Change to 3</a>

    <script>

    $("#btn-change-option").click(function(){

         // get option to select from the data attribute of your link
         var optionToSelect = $(this).data('option');

         $('select>option:eq('+optionToSelect +')').attr('selected', true);

    })

    </script>
Thanassis_K
  • 272
  • 1
  • 9