0

I have a string UserLevel and I want to set the dropdown list value to the item that matches this string. I have tried this:

$("#Level option:selected").val(UserLevel);

But it didn't work.

and I don't know how to use this:

$("#Level option[value='']").attr("selected", "selected");

Is there any other way?

1
  • 1
    is your UserLevel a variable or is that the string? Commented Aug 25, 2014 at 5:51

2 Answers 2

2

Just do this :

$("#Level").val(UserLevel);  //here 'Level' is dropdown 'id'

and if 'UserLevel' is a string then there could be white space problem also then do as :

$("#Level").val($.trim(UserLevel));  //Use $.trim() here to remove white spaces.

and make sure values inside dropdown are also trimmed.

Above code will work here is fiddle code provided by @HowieH

Link :-http://jsfiddle.net/hhalse/s4qwaLgd/

Sign up to request clarification or add additional context in comments.

4 Comments

just see there is any value inside dropdown same as UserLevel??..@Mary
I did! It works when I use a direct string, $("#Level").val("text");. but not with the variable.
Normally what @Exception is suggesting should work, see this jsfiddle . Could you provide us with some more details?
Yepp!! tanx a lot! @Exception
0

You can do like this.

var text = "UserLevel";
$("#Level option:contains(" + text + ")").attr('selected', 'selected');

or iterate each value then compare.

   $("#Level option").each(function() {
  if($(this).text() == text) {
    $(this).attr('selected', 'selected');            
  }                        
  });

or you can use val to set the value directly. Here's how.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.