Change the Text of a Option with jQuery

How can I change the text of an option with jQuery?

I’d like to change Newest with Oldest in an option is a <select> element.

$('select option:contains("Newest")').changeText('Oldest');

.replaceWith would not work for me.

Thanks.

—-Update—-

If my script looks like this:

$('select option:contains("Newest")').text('Oldest');
$('select option:contains("Oldest")').text('Newest');

Then I’m canceling out the first script, however, that isn’t what I want. I have two options one that reads “Newest” which I’d like to replace with “Oldest” and one that reads “Oldest” which I’d like to replace with “Newest”. How can I accomplish that?

You should start a new question but here’s the answer:

$('select option:contains("Newest")').text('TEMPEST');
$('select option:contains("Oldest")').text('Newest');
$('select option:contains("TEMPEST")').text('Oldest');

$('select option:contains("Newest")').each(function(){
   var $this = $(this);

   $this.text($this.text().replace("Newest","Oldest"));    
});​

http://jsfiddle.net/eSa5p/

EDIT: Answer to the new question:

var $newest = $('select option:contains("Newest")');

$('select option:contains("Oldest")').text('Newest');
$newest.text('Oldest');

http://jsfiddle.net/eSa5p/3/

$("#mySelect option").html(function(i,str){
  return str.replace(/Newest|Oldest/g,  // here give words to replace
     function(m,n){
         return (m == "Newest")?"Oldest":"Newest";  // here give replacement words
     });
});

demo : http://jsfiddle.net/diode/eSa5p/2/

Change text of the selected option:

$(“#select”).find(“option:selected”).text(‘Newest’);

You can do that by a simple script

$("option[value=optionvalue]").html('New text');

$('select option:contains("Newest")').addClass('changeToOldest');
$('select option:contains("Oldest")').addClass('changeToNewest');
$('.changeToOldest').text('Oldest').removeClass('changeToOldest');
$('.changeToNewest').text('Newest').removeClass('changeToNewest');


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Why does this javascript based printing cause Safari to refresh the page?

Similar Posts