Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() not setting the value of <select>

I would like to know why jQuery's .val() function is not setting the value of the <select> control for me after I called replaceWith, but it is working otherwise.

Please see here for a (not) working example.

<select><option>ABC</option><option>DEF</option></select>
<input type="button" onclick="ControlOff()" value="Turn Off Control" />
<input type="button" onclick="ControlOn()" value="Turn On Control" />
<input type="button" onclick="Test()" value="Value Setting Test" /> 
function ControlOff() {
    $('select').each(function () {
        $(this).replaceWith('<span class="select-type">' + $(this).val() + '</span>');
    });
}

function ControlOn() {
    $('.select-type').each(function () {
        var selected = $(this).text();
        $(this).replaceWith('<select><option>ABC</option><option>DEF</option></select>');
        $(this).val(selected);
    });
}

function Test() {
    $('select').val('DEF');
}
like image 626
user1589188 Avatar asked Oct 07 '22 10:10

user1589188


1 Answers

The problem is, that $(this) in $(this).val(selected) refers to the removed <span> element, not your new element. You need to replace it with:

$('select').val(selected);

to grab the previously inserted new element.

Also, your code is unecessarily complex, this does the same thing, but simpler:

function ControlOn() {
    $selectText = $('.select-type');
    var selected = $selectText.text();
    $selectText.replaceWith('<select><option>ABC</option><option>DEF</option></select>');
    $('select').val(selected); // Use an id instead to match: #my-select-id
}

Make sure to give the <select> element an ID, otherwise it's going to mess up once you introduce a new <select> element somewhere else on the page.

See here for a working example.

like image 184
phant0m Avatar answered Oct 09 '22 00:10

phant0m