I have a field that represents a zip code of a user. When the user leaves that text box, an AJAX request is sent to the server to receive cities that may be associated with that zip code.
I am trying to use the JSON received from that request to populate a select list to replace the text box that is currently assumed for city (if one city is returned, I just change the value of the text box).
For example, a user puts in 20910 as their zip code and it returns Silver Spring. I replace the textbox for city with Silver Spring. Another user puts in 84107 as their zip code and it replaces the textbox with a select list of Murray, Salt Lake City.
It receives the JSON just fine, but I am not sure if I am doing something wrong in my JavaScript. When the select is rendered, it gives blank fields after each value.
Here is my jQuery:
$('#AddressData_ZipCode').blur(function() {
var zip = $('#AddressData_ZipCode').val();
var pattern = /^\d{5}([\-]\d{4})?$/;
if (zipCode.length > 0 && pattern.test(zip)) {
$.getJSON("/GeneralInfo/GetCitiesInZip", { zipCode: zip }, function(data) {
if (data.length > 1) {
var citiesComboBuilder = "<select id='AddressData_City'>";
for (var i = 0; i < data.length; i++) {
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "<option/>";
}
citiesComboBuilder += "</select>";
$('#AddressData_City').replaceWith(citiesComboBuilder);
}
else
$('#AddressData_City').val(data);
});
}
});
This is the returned JSON: ["Murray","Salt Lake City"]
And this is the HTML that I receive after the function runs:
<select id="AddressData_City">
<option value="Murray">Murray</option>
<option/>
<option value="Salt Lake City">Salt Lake City</option>
<option/>
</select>
Any help would be great. Any suggestions to improve this code would be great also. Thanks.