0

I have a dropdown box, It has no values in them. I have to set it preselected with a value available in a variable. This is what I have done but it does not set this value.

if(condition)
{
    var selectedVal = "myValue";                
    $("#myDropDownId").val(selectedVal);
}

as per info from google, the above one works when there are options already available in the dropdown.

I tried with the below as well

if(condition)
{
    var selectedVal = "myValue";                
    $("#myDropDownId option:selected").val(selectedVal);
 }  

What is the correct syntax for this please?

3
  • Do you mean there are no option elements inside the select? If that's the case, you probably want to add one with a value/text matching the value of your variable, rather than trying to set the select value. Commented Feb 17, 2012 at 10:07
  • why using drop down when you need to select a single value; in any case if you want to select a value you need to have it available as one of the options Commented Feb 17, 2012 at 10:12
  • @StewieFG. Are you still having difficulties? Commented Feb 17, 2012 at 11:37

3 Answers 3

1

The code in your first example is the correct method and should work fine; see this fiddle.

Are you using Firefox? If so, don't forget it keeps the state of a form on refresh, and does not pick the default values. Try pressing CTRL+F5 to force it to completely refresh the page and reset the form to initial defaults.

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

Comments

0

add this in your select

<option value="myValue">MY VALUEEEEE</option>

Comments

0

This will do it:

var selectedVal = "myValue";
$("#myDropDownId").append('<option selected="true" value=' + selectedVal + '>' + 
                            selectedVal + '</option>');​

JSFiddle DEMO

(You can delete the selected="true" part if you don't want that option be selected)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.