'JQuery String Replacement in Select List
I have the following dropdown list being generated from a database query which includes two "dividers" and looks like this:
<select id="mySelectList">
<option value="divider::: --- Popular Brands ---">divider::: --- Popular Brands ---</option>
<option value="apple">Apple</option>
<option value="samsung">Samsung</option>
<option value="divider::: --- All Brands ---">divider::: --- All Brands ---</option>
<option value="acer">Acer</option>
<option value="apple">Apple</option>
</select>
For both occurrences, I would like to replace the option value to be "" and to remove the string divider::: from the option text. So the end result would look like this:
<select id="mySelectList">
<option value="">--- Popular Brands ---</option>
<option value="apple">Apple</option>
<option value="samsung">Samsung</option>
<option value="">--- All Brands ---</option>
<option value="acer">Acer</option>
<option value="apple">Apple</option>
</select>
I'm using jQuery and have this, but the result isn't what I'm trying to acheive.
$("#mySelectList option").each(function() {
$(this).text($(this).html().replace(/divider:::/g, ""));
});
Solution 1:[1]
Rather than iterating over every option, I'd use pattern matching selectors, eg the starts-with selector:
$('option[value^=divider]').attr('value', '')
.text(function() {
return $(this).text().replace('divider::: ', '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelectList">
<option value="divider::: --- Popular Brands ---">divider::: --- Popular Brands ---</option>
<option value="apple">Apple</option>
<option value="samsung">Samsung</option>
<option value="divider::: --- All Brands ---">divider::: --- All Brands ---</option>
<option value="acer">Acer</option>
<option value="apple">Apple</option>
</select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Don't Panic |
