2

In the first step, I have a set of values which are fed to a dropdown.

In the next step, I want to SET the value of the dropdown from the set of the values which are fed to it in the first step.

Could anyone let me know the syntax in jquery?

apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
user2437845
  • 61
  • 1
  • 1
  • 4
  • 1
    http://api.jquery.com/val/ – Adil Shaikh Jun 20 '13 at 19:28
  • Have you tried anything yet? You will probably get more response if you post code you have tried or are currently working on. – zxqx Jun 20 '13 at 19:28
  • Yes I had tried, but in javascript. But the code didn't worked. So I thought of writing jquery, I have searched in the google, but ended up with many syntax. I want to know the correct way, or else I will implement and let you know it tomorrow. Thanks for the prompt response – user2437845 Jun 20 '13 at 19:32
  • To show you the syntax, it would be helpful to see what your "set of values" looks like -- even a simplified example. What are you working with, what does it look like? – cssyphus Jun 20 '13 at 20:17

1 Answers1

3

If it is, say, the 4th item in the dropdown, you can say:

$('select>option:eq(3)').prop('selected', true);  //zero-based

Note that older versions of jQuery used .attr instead of .prop


Here are some other methods:

Imagine a select box like this:

<select name="options">
  <option value="1">Red</option>
  <option value="2" selected="1">Green</option>
  <option value="3">Blue</option>
</select>

You can get the 3rd value this way:

$('[name=options]').val( 3 );//To select Blue

Using the text:

$('[name=options] option').filter(function() { 
    return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);

Reset it this way:

$('[name=options]').val( '' );
cssyphus
  • 37,875
  • 18
  • 96
  • 111