The process is simple:
HTML
<asp:DropDownList ID="d" runat="Server" AppendDataBoundItems="true"/>
<asp:TextBox ID="t" runat="Server" AutoPostBack="true" onchange="if(!test(this)) return false;"/>
JQUERY
$(function test() {
var d = ('#<%= d.ClientID%>'),
t = ('#<%= t.ClientID%>');
$(d + ',' + t).on('change', function () {
var val = this.value;
$(d + ' option').each(function () {
if (this.value == val) {
$(d + ',' + t).val(val);
return false;
}
return true;
});
});
});
This code works perfectly for updating the dropdown value. The problem is this code prevents postback in all cases.
I think the problem is that onchange is fired from textbox and then the subsequent code inside the javascript onchange will not work.
Try javascript:return test()
instead of if(!test(this)) return false;
, like this
<asp:TextBox ID="t" runat="Server" AutoPostBack="true"
onchange="javascript:return test()"/>
and in JavaScript
function test() {
var d = document.getElementById('d'), t = document.getElementById('t');
var ddl = ('#d');
var txt = ('#t');
var val = t.value;
var len = $(ddl+ ' option[value=' + val + ']').length;
if (len > 0) {
d.value = t.value = val;
return false;
}
return true;
}
Update
Aspx
<asp:DropDownList ID="d" runat="Server" AppendDataBoundItems="true" onchange="javascript:return test('ddl')"/>
<asp:TextBox ID="t" runat="Server" AutoPostBack="true" onchange="javascript:return test('txt')" />
JavaScript
function test(temp) {
var d = document.getElementById('<%= d.ClientID%>'), t = document.getElementById('<%= t.ClientID%>');
var ddl = ('#<%= d.ClientID%>');
var txt = ('#<%= t.ClientID%>');
var val = t.value;
if (temp == "txt") {
var len = $(ddl + ' option[value=' + val + ']').length;
if (len > 0) {
d.value = t.value = val;
return false;
}
}
else {
t.value = d.value;
return false;
}
return true;
}
You can use __doPostBack instead.
post back when drop down list changed:
$(function() {
var d= $('#<%= d.ClientID%>');
d.removeAttr('onchange');
d.change(function(e) {
//You can decide when to post back
setTimeout('__doPostBack("<%= d.ClientID%>","")', 0);
});
});
or post back when textbox changed
$(function() {
var t= $('#<%= t.ClientID%>');
t.removeAttr('onchange');
t.change(function(e) {
setTimeout('__doPostBack("<%= t.ClientID%>","")', 0);
});
});
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.