开发者

How to remove text from each select option using jQuery

I have a list of options that looks like this:

<select id="input_13">
        <option class="level-1" value="35">&nbsp;&nbsp;&nbsp;Eielson AFB</option> 
    <option class="level-1" value="36">&nbsp;&nbsp;&nbsp;Elmendorf AFB</option> 
    <option class="level-1" value="37">&nbsp;&nbsp;&nbsp;Fort Greely</option> 
</select>

How can I use .replace to move through each o开发者_如何学Pythonption and take out all the spaces?

So far I've tried this, which is not working:

jQuery("#input_13).each(function () {
            (this).text().replace('&nbsp','1234');
});


try this:

 $("#input_13").find("option").each(function (index, option) {
        $(option).html($(option).html().replace(/&nbsp;/g,''));
 });

jsFiddler: http://jsfiddle.net/rwWv7/5/


jQuery("#input_13")

The mistake here is that you are selecting the select element so each will only loop through select.

$(this).text().replace('&nbsp','1234');

The mistake here is that you are replacing &nbsp with 1234 but are not assigning it back to the element. Also it would only replace the first &nbsp. html is a better option here as text would convert &nbsp to space.

The correct code would be:

$("#input_13 option").each(function () {
    $(this).html($(this).html().replace(/&nbsp;/g,''));
});

Looks like the server-side code is generating the &nbsp's. If possible it would be better to modify the server-side code to not generate them rather that using JavaScript to remove them.


This should work:

jQuery("#input_13 option").each(function () {
    $(this).text($(this).text().replace(/\u00a0/g,''));
});

Note that it's using the unicode equivalent of &nbsp; to replace.

fiddle: http://jsfiddle.net/bjorn/2Rfmw/14/


You have to use html() so that the &nbsp; are taking literally. You can also pass a function to html() which makes things very easy:

$('#input_13 option').html(function(i, html) {
    return html.replace('/&nbsp;/g','');
});

Two things to note: replace returns the new string and you need a regular expression, because be default, replace only replaces the first occurrences of the search string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜