jquery selectbox to textbox - ajax based

As an answer to http://stackoverflow.com/questions/33322730/jquery-selectbox-to-textbox/33377345

by marson parulian

HTML

<select id="country">
    <option value="Türkiye">Turkey</option>
    <option value="UK">United Kingdom</option>
    <option value="USA">USA</option>
</select>
<select id="city">
    <option value="Izmir">Izmir</option>
    <option value="Ankhara">Ankhara</option>
</select>
<select id="town">
    <option value="bergama">Bergama</option>
    <option value="bornova">Bornova</option>
    <option value="buca">Buca</option>    
</select>

JavaScript

$(document).ready(function () {
    var city = $('#city');
    var town = $('#town');
    $('#country').change(function () {
        var country = $(this).val();
        if (country != 'Türkiye') {
            $('#city').replaceWith('<input class="form-control" type="text" name="city" id="city">');
            $('#town').replaceWith('<input class="form-control" type="text" name="town" id="town">');
        } else {
            $('#city').replaceWith(city);
            $('#town').replaceWith(town);
        }
    });
    // Need to attach event handlers for newly inserted city options
    $(document).on('change','#city' ,function(){
    	var city = $(this).val();
        requestTownList(city);
	});
    // Handle town list acquired from AJAX
    var handleTownList = function(townList){
		// Clear town options 
        $("#town").html("");
        // Then append town names based on selected city
        for(var i=0; i<townList.length; i++){
      		$("#town").append("<option value='"+townList[i].id
			+"' >"+townList[i].text+"</option>");  
		}
	};
    // Lines below are mocking AJAX request-response
    var requestTownList = function(cityId){
        // Define result that will be returned by AJAX response
        var townList;
        if(cityId == "Izmir"){
            townList = [
                {id: 'bergama',text:"Bergama"},
                {id: 'bornova',text:"Bornova"},
                {id: 'buca',text:"Buca"}];
        }else if( cityId= "Ankhara" ){
            townList = [
                {id: 'bala',text:"Bala"},
                {id: 'evren',text:"Evren"},
                {id: 'mamak',text:"Mamak"}];    
        };
        // Mock AJAX request
        $.ajax({
            url: '/echo/json/',
            type: 'POST',
            data: "val=myvalue",
            success: function(d){
                // FIXME: list of town should be acquired from server.
                // Will be delay, caused by jsfiddle's AJAX mocking.
               ...