PHP Dev PHP Dev - 1 month ago 5
jQuery Question

using replaceWith in jquery input textbox to select dropdown

I have this jQuery code. My problem is that I want to replace the textbox

input
with a
select
dropdown using jQuery. Here is my code:

jQuery(document).ready(function($) {
var select = $("<select>").addClass("form-group");

var request = {
'action': 'zipcode'
};

$.getJSON(zibbra.getAjaxUrl(), request, function(response) {
var error = $("<select>")
$.each(response, function(i, field){
$('#billing_zipcode').append($('<option>', {
value: field.id,
text: field.zipcode
}));
});
$("#billing_zipcode").replaceWith(dropdown);
});
});


<input id="billing_zipcode" name="billing[zipcode]" value="" type="text">


It seems it's not working. Can someone help me figured this thing out? Any help is muchly appreciated. TIA

Answer

You are trying to create select element and you forget to append options into it

jQuery(document).ready(function($) {
    var select  = $("<select>").addClass("form-group");

    var request = {
        'action': 'zipcode'
    };

    $.getJSON(zibbra.getAjaxUrl(), request, function(response) {
        var dropdown = $("<select>");
        $.each(response, function(i, field){
            dropdown.append($('<option>', {
                value: field.id,
                text: field.zipcode
            }));
        });
        $("#billing_zipcode").replaceWith(dropdown);
    });
});
Comments