You know, sometimes small things will take long time to implement. Usually this will happen if we are not familiar with them. For this, plenty of documentation is available around, we should read it before starting it. So, here I am talking about JQuery and the features of it. I know how to select a value in a drop down and populate it using plain javascript. But when comes to JQuery, for me it took sometime to find a way to do that. Below is the way on how to populate a dropdown value as selected.
$("#ddlSource option[value='1']").attr("selected", "selected");
Here, ddlSource is the ID of the HTML select [drop down list] control. The meaning of the above statement is, find the control which has the ID "ddlSource" and in it find the option which has give value and select it. "1", I am using for example. You can pass any value.
If you are using the server side controls, and want to populate the value in JQuery, then use below statement.
$("#<%=ddlSource.ClientID %> option[value='1']").attr("selected", "selected");
But this is not the right way of doing it. You can change the server side drop down values on client side, but which results you the error message "Invalid Postback or Callback event" when submitting data to server. So, take care when you deal with server side controls in javascript.
For best practice Please try to use <select runat="server" ID="ddlSource" ></select> instead of <asp:DropDownList /> to avoid the invalid callback error messages. I know, the immediate question in your mind, how to get the value using <select> control in C# code. Use below code for it.
string selectedValue = Request.Form[ddlSource.UniqueID]; //UniqueID is because Form is expecting name instead of ID.
Is this helpful?
Have You tried the Sam's code I use in my interface ? It's pretty nice tool to manage options.
ReplyDeletehttp://patidure.blogspot.com/2009/08/jquery-remove-for-html-select-options.html
I've just spent an hour and a half trying to find out how to do that.
ReplyDeleteYou deserve a much higher ranking in google!
an easier way to type this is:
ReplyDelete$("ddlSource").val('1').attr("selected", "selected");
I wasted many hours in finding this!.. many thanks to your post!
ReplyDeleteor you can do something easier
ReplyDelete$('#dropdownid').val('value');
its perfectly fine with the value.. but i want to select the value based on the text.
ReplyDeleteHow to achieve that?
dude, right on! Didn't spend hours on this thanks to you. Thank you!
ReplyDeleteVery useful, thank you
ReplyDeleteExcelente....Preciso y Conciso....Para mi caso, funciona de maravilla. Felicitaciones...Saludos.
ReplyDeleteThanks a ton ... you do deserve higher google ranking.
ReplyDeleteThanks a ton ... you do deserve a higher ranking on google.
ReplyDeleteThanks a million!!!
ReplyDeleteGood one!!!
ReplyDelete