ToniWidmo
ToniWidmo

Reputation: 509

Escaping select option values in jquery

I have a bunch of select boxes used to filter a large complex table whose contents is loaded via a sequence of ajax queries. As the table loads, not just the table but the select box filter update to reflect the current available options. As the use may already have selected options to filter the table at this point, I have a bit of code to preserve the currently selected value:

    if($('#CourseFilter').length) {
        selected = $('#CourseFilter').val();
        $('#CourseFilter').replaceWith(sel);
        if(selected != '') $('#CourseFilter option[value="'+escape(selected)+'"]').prop('selected', true);
    } else {
        sel.appendTo('#filters'); // Adding fitler for first time.
    }

This works for most of the filters, but a couple, such as #CourseFilter, reset back to default instead of remembering current selection. It think it is because the values in these lists contain special characters such as -, / and \. I have tried using escape but it still doesn't work. Any ideas?

Upvotes: 1

Views: 1031

Answers (2)

Mate Solymosi
Mate Solymosi

Reputation: 5977

What you are probably looking for:

You should be able to just set the value of sel, instead of finding the right <option> and manually selecting that:

sel.val(selected);

If you want to find the right <option>:

You can avoid the escaping issue altogether by filtering for the right <option> using jQuery.filter:

$('#CourseFilter option').filter(function() {
  return $(this).val() === selected;
}).prop('selected', true);

Upvotes: 1

charlietfl
charlietfl

Reputation: 171690

No need to look for each <option> since val() is both a getter and a setter.

Just use val() to set value on new <select>

if($('#CourseFilter').length) {
    selected = $('#CourseFilter').val();
    $('#CourseFilter').replaceWith(sel);
    sel.val(selected);
} else {
    sel.appendTo('#filters'); // Adding fitler for first time.
}

Upvotes: 1

Related Questions