53

I have many options in my dropdownlist like:

<option value="1">it's me</option>

I need to select the option who have value it's me inside the tag, not by attribute like 1.

How can I do this using jQuery?

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • Well i want to select them through the 'it'sme' value. but very few of us try to do with it.but thanks to all ! –  Jan 24 '11 at 11:45
  • $("#myCombobox option[text='it\'s me']").attr("selected","selected"); – ashish.chotalia Jan 24 '11 at 11:53
  • http://stackoverflow.com/questions/292615/how-can-i-set-the-value-of-a-dropdownlist-using-jquery Try this one.. – Clyde Apr 16 '13 at 08:29

8 Answers8

107

if your wanting to use jQuery for this, try the following code.

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

Updated:

Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.

Here below is the updated code.

$('select option:contains("it\'s me")').prop('selected',true);

You need to use the :contains(text) selector to find via the containing text.

Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.

A working example on JSFiddle

kylewelsby
  • 4,031
  • 2
  • 29
  • 35
47

You can just do this:

$('#myCombobox').val(1)
Hogsmill
  • 1,574
  • 13
  • 21
7

val() should handle both cases

  <option value="1">it's me</option>      


$('select').val('1'); // selects "it's me"

$('select').val("it's me"); // also selects "it's me"
4
$('#userZipFiles option').prop('selected', function() {
        return this.defaultSelected;
    });     
Franco
  • 2,309
  • 1
  • 11
  • 18
2
$("#dropdownList option[text='it\'s me']").attr("selected","selected"); 
Vivek
  • 10,978
  • 14
  • 48
  • 66
1
jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");
Harish
  • 2,311
  • 4
  • 23
  • 28
0

This is working fine:

$('#country').val($("#country option:contains('It\'s Me')").val());
ashish.chotalia
  • 3,696
  • 27
  • 28
0

One line of jQuery does it all!

$("#myCombobox option[text='it\'s me']").attr("selected","selected"); 
Mark Robinson
  • 13,128
  • 13
  • 63
  • 81
  • Won't you have problems with the quotes within quotes? How will JQuery know what's going on if your inner double quotes are not escaped? Perhaps I'm missing something here? – jamesmortensen Jan 24 '11 at 11:40
  • @jmort253 - if you are consistent you can mix single and double quotes as long as you use one to mark the outer string and the other to use internally in the string. Eg. "This is valid ''' :) " and "This is invalid """ :(". – Mark Robinson Jan 24 '11 at 11:48