Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

How could I set the value in to dropdownlist dynamically using jquery

I have checked The below three methods and failed

Temp is a dynamic value
JavaScript
$('#dptcentres_edit').val(temp).attr("selected", "selected");
$("#dptcentres_edit option[value='"+ temp +"']").attr("selected", "selected");
$("#dptcentres_edit").val(temp);


Please help me

Thanks & Regards,
soumya
Posted
v2

Problem
I guess the problem here is, the option is not present inside the DropDownList.

So, the below code should work for you, if you already have the temp option.
JavaScript
$("#dptcentres_edit > [value=" + temp + "]").attr("selected", "true");


Solution
If you don't have the option inside the DropDownList, then you need to append that first and then select it.

So, the below code is what you need.
JavaScript
// Create New Option.
var newOption = $('<option>');
newOption.attr('value', temp).text(temp);

// Append that to the DropDownList.
$('#dptcentres_edit').append(newOption);

// Select the Option.
$("#dptcentres_edit > [value=" + temp + "]").attr("selected", "true");


Demo
[Demo] Dynamically Set and Select the DropDown Option[^]
 
Share this answer
 
do this way...
$("#dptcentres_edit option[value='"+ temp +"']").attr("selected", "selected");
$('#dptcentres_edit').val(temp).change();

good luck !
 
Share this answer
 
Comments
Member 14576736 4-Sep-19 1:03am    
Worked in 1st attemp, 100%
Thank you very much! it worked for me too after hours of crying!
 
Share this answer
 
Comments
Richard Deeming 24-Jun-22 5:37am    
If you want to reply to a solution, click the "Have a Question or Comment?" button under that solution and post a comment.

Do not post your comment as another "solution" to the question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900