Home > OS >  Why can't I replace option value?
Why can't I replace option value?

Time:07-15

I'm trying to modify the displayed option values on this page (click "More Options" to expand parameters: https://jobs.sap.com/?utm_source=careersite&utm_campaign=Top_Button

However, it appears that for some reason I cannot change the values for any of the options, only for the placeholder value. I'm trying to do it like this:

$("document").ready(function() {
$("#optionsFacetsDD_department option").text($("#optionsFacetsDD_department 
option").text().replace("Administration", "Admin"));
}); 

Any ideas why this doesn't work?

CodePudding user response:

The problem is because you're using $("document"), which is telling jQuery to find a <document /> element in the DOM - which will never exist, instead of $(document).

$(document).ready(function() {
  $("#optionsFacetsDD_department option").text($("#optionsFacetsDD_department option").text().replace("Administration", "Admin"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select id="optionsFacetsDD_department">
  <option>Foo Administration</option>
</select>

Also note that you can improve the code by providing a function to text() which accepts the current text value as an argument. You can then call replace() on that without having to access the DOM once more to get the text of the element which you already have a reference to. Try this:

jQuery($ => {
  $("#optionsFacetsDD_department option").text((i, t) => t.replace("Administration", "Admin"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select id="optionsFacetsDD_department">
  <option>Foo Administration</option>
</select>

  • Related