If my dropdown has a value selected, I want to show the selected item text in my textbox. If not, I want to empty it.
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onselectedindexchanged="ddlSelectedIndexChanged" Width="200px" onchange="ddlChange()">
</asp:DropDownList>
<asp:TextBox ID="hdntxtbxTaksit" runat="server" Visible="false"></asp:TextBox>
How can I do this?
If you want to assign selected value of dropdownlist to text box you can assign in change event without and condition as change event means dropdown have been selected
.
With javascript
Change
onchange="ddlChange()"
To
onchange="ddlChange(this)"
Your javascrpt method would be
function ddlChange(ddl)
{
document.getElementById('<%= hdntxtbxTaksit.ClientId %>').value = this.value;
}
With jQuery
Remove onchange="ddlChange()" as we will bind event with jquery.
$('<%= ddl.ClientId %>').change(function(){
$('<%= hdntxtbxTaksit.ClientId %>').val($(this).val());
});
Using jQuery;
$().ready(function(){
$('#<%=ddl.ClientID %>').change(function () {
$('#<%=hdntxtbxTaksit.ClientID %>').val($(this).val() == "0" ? "" : $(this).val());
});
});
EDIT: With above method, you don't need to call onchange
event of the dropdown. So your markup can be
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlSelectedIndexChanged" Width="200px">
</asp:DropDownList>
<asp:TextBox ID="hdntxtbxTaksit" runat="server" Visible="false"></asp:TextBox>
you can do it like this
function ddlChange()
{
if(document.getElementById('<%= ddl.ClientId %>').value=='0')
{
document.getElementById('<%= hdntxtbxTaksit.ClientId %>').value = "";
}
else
{
document.getElementById('<%= hdntxtbxTaksit.ClientId %>').value = document.getElementById('<%= ddl.ClientId %>').value;
}
}
Try this code and remove onchange event added in your asp:dropdownlist
Note: AUTOPOSTBACK property will always do a page submit, it wont stop even if you return false in onchange method of dropdown
$(document).ready(function () {
$('#<%=ddl.ClientID %>').change(function () {
if ($(this).val() != "0") {
$('#<%= hdntxtbxTaksit.ClientID %>').val($(this).val());
}
else {
$('#<%= hdntxtbxTaksit.ClientID %>').val("");
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.