Search code examples
jquerydrop-down-menuspacesselected

Remove spaces from selected state in option dropdown on change event


In a data query, I get a tree structure:

<select name="parent" id="select_parent">
<option> >Administrator </option>
<option> &nbsp;>Manager </option>
<option> &nbsp;&nbsp;>Sales </option>
<option> &nbsp;&nbsp;>Operator </option>
<option> &nbsp;>Promoter </option>
</select>

Obviously this looks good on the combobox options, But when I select a value ... this is shown complete with spaces. What I want is to remove spaces when it is only a selected value.

I tried this:

$('#select_parent').bind("change",function()
{
    var s = $('#select_parent option:selected').html();
    $('#select_parent option:selected').html(s.replace(/&nbsp;/g, ''));
});

But after eliminating the spaces ... they will return to see if the item no longer has the selected attribute?


Solution

  • If you'd like to display the selected list item still with the spacing while removing the spacing only in the select's displayed text, you can try this hack:

    $('#select_parent').bind("change", function() {
        var space_offset = 8;
        var matches = $('#select_parent option:selected').text().match(/\s+?/g);
        var n_spaces = (matches) ? matches.length : 0;
        $(this).css('text-indent', -(n_spaces*space_offset));
    });
    

    The select's text property is immutable, therefore I made a small css hack to un-indent the selected option's text inside the select's display based on how many spaces it has.

    JSFiddle

    Don't forget to remove any extra spacing besides &nbsp; insde your options' texts and adjust the space_offset to match the width of a space character in pixels, if your page uses a different font or font size.

    edit: I tested it on Chrome only, for Firefox it'd require extra css hacking.

    edit: Alright, here's my final version without any css hack:

    var trig = ($.browser.mozilla) ? 'click' : 'mousedown';
    $(function() {
        $('#select_parent').on("change", function() {
            var sel = $('#select_parent option:selected');
            $(this).data('cur_val', sel);
            var display = sel.clone();
            display.text($.trim(display.text()));
            sel.replaceWith(display);
            $(this).prop('selectedIndex', display.index());
        }).on(trig, function() {
            if ($(this).prop('selectedIndex') == 0)
                return;
            var sel = $('#select_parent option:selected');
            sel.replaceWith($('#select_parent').data('cur_val'));
            $(this).prop('selectedIndex', 0);
        });
        $('#select_parent').change();
    });
    

    JSFiddle

    Tested on Firefox, Chrome, IE and Opera. Should work on Safari as well, as it is Webkit-based.