I am trying to auto fill city and state value after user typing 5-digit zip code. The Ajax part works perfectly, the problem is I have two sets of zip/city/state fields in one web page. I searched this issue for quite a while, using next(),nextAll() even slice(), none of them work in my situation.
Web page related part:
<table>
<tr>
<td align="right" class="style3">ZIP:</td>
<td>
<asp:TextBox ID="tb_ZIP" runat="server" Width="100px"
alt="zip5" class="zip"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="style3">City:
<td>
<asp:TextBox ID="tb_City" runat="server" Width="100px"
class="city"></asp:TextBox>
</td>
<tr>
<td align="right" class="style3">State:</td>
<td>
<asp:DropDownList ID="ddl_State" runat="server"
Width="100px" class="state"></asp:DropDownList>
</td>
</tr>
<tr>
<td align="right" class="style2">ZIP:</td>
<td>
<asp:TextBox ID="tb_AffiOrComZIP" runat="server"
Width="100px" alt="zip5" class="zip"
ontextchanged="tb_AffiOrComZIP_TextChanged">
<tr>
<td align="right" class="style2">City:</td>
<td>
<asp:TextBox ID="tb_AffiOrParCity" runat="server"
Width="100px" class="city"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="style2">State:</td>
<td>
<asp:DropDownList ID="ddl_AffiOrParComState"
runat="server" Width="100px" class="state">
</asp:DropDownList>
</td>
</tr>
</asp:TextBox>
</td>
</tr>
</td>
</tr>
</table>
JS:
$(".zip").each(function() {
var zipTextBox = $(this);
zipTextBox.keyup(function() {
var zip = $(this).val();
if (zip.length == 5) {
$.post(rootPath + "/AjaxPages/DropdownData.aspx", {
"inputValue": zip,
"type": "zip"
}, function(data) {
var cityStr = $(data).attr("city");
var stateStr = $(data).attr("state");
$(this).nextAll(".city:first").val(cityStr); //this doesn't work
for (var i = 0; i < $(this + ".state option").length; i++) { //this works for first
if ($(this + ".state").get(0).options[i].text == stateStr) {
$(this + ".state").get(0).options[i].selected = true;
break;
}
}
});
}
});
});
After using Ajax function I get returned value for city and state. For each city textbox I give a “city” class, for each state dropdownlist I give a “state” class. I wonder how can I put those value into right position? Any help is appreciated. Thank you in advance.
The problem is that the elements with classes
zipandcityare not siblings. Try this:Unfortunately, you keep editing the markup in your question, so I’m taking a bit of a guess at the actual HTML you need to traverse.