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?
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.