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"> Eielson AFB</option>
<option class="level-1" value="36"> Elmendorf AFB</option>
<option class="level-1" value="37"> 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(' ','1234');
});
try this:
$("#input_13").find("option").each(function (index, option) {
$(option).html($(option).html().replace(/ /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(' ','1234');
The mistake here is that you are replacing   with 1234 but are not assigning it back to the element. Also it would only replace the first  . html is a better option here as text would convert   to space.
The correct code would be:
$("#input_13 option").each(function () {
$(this).html($(this).html().replace(/ /g,''));
});
Looks like the server-side code is generating the  '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
to replace.
fiddle: http://jsfiddle.net/bjorn/2Rfmw/14/
You have to use html()
so that the
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('/ /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.
精彩评论