changing text input to select in wordpress using jQuery

I am using a WordPress module abase to get some data from database and send them to a form. The problem is, that abase form does not allow to use select input. Because of that I am trying to convert text input to a select. I created function toSelect, to which I pass id of element and list of options (for testing I put id of element to function definition).

function toSelect(itemid,valuelist) {
    var out = '';
    out += '<select id="bus311mtd_2_status" style="width:50px;">';
    for (i=0; i < valuelist.length; i++) {
        out += '<option value="'+valuelist[i]+'">'+valuelist[i]+'</option>';
    }
    out += '</select>';
    alert(out);
    $("#bus311mtd_2_status").replaceWith(out);
    //$("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">');
}

alert(out) gives nice select input code, but $("#bus311mtd_2_status").replaceWith(out) does not work.

Read More

Even something like: $("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">') doesn’t work.

Element with id bus311mtd_2_status for sure exists (i.e. changing its value using document.getElementById() works fine)

Maybe jQuery doesn’t work?

Related posts

2 comments

  1. Your code seems to work fine for me. Perhaps it’s your function call. I used:

    toSelect(null, ['a', 'b', 'c']);
    

    itemid doesn’t appear to be used in the function.

    Here’s a fiddle with your code working:
    http://jsfiddle.net/dgrundel/Lko6aftf/

    Here’s a slightly optimized version of the function, that uses the itemid argument:

    function toSelect2(itemid,valuelist) {
        var html = '<select id="' + itemid + '" style="width:50px;"><option>' +
            valuelist.join('</option><option>') +
            '</option></select>';
        $('#' + itemid).replaceWith(html);
    }
    
    toSelect2('myInput2', ['d', 'e', 'f']);
    
  2. Thank you for the answer and optimization. I used itemid initially but because of problems I temporarily replaced it with id of some existing element to make sure that the problem is somwhere else.

    All the code until first alert works fine and alert(out) gives the popup window with text:

    <select id="bus311mtd_2_status" style="width:50px;"><option value="ready">ready</option><option value="awaiting">awaiting</option></select>
    

    This works as was expected. But the problem starts with the next line.

    I wanted to show that even such an easy code like below doesn’t work.

    $("#bus311mtd_2_status").replaceWith('<input type="text" value="zamontowane">');
    

    So it looks like the jQuery was not supported.

    And I’ve got another observation: within script tags no empty lines are allowed (the code doesn’t work if they are present).

Comments are closed.