Curtis
Curtis

Reputation: 2704

change selectbox text using jQuery

Basically, I have a jQuery modal that's getting content dynamically via an onClick then using the data attributes, I need to replace text inside a <select></select> to display an dynamic email address.

Here's the HTML

<select name="email" class="span4">
    <option id="holder" value="">Ticket Holder ('{ticket_holder}')</option>
    <option id="purchaser" value="">Ticket Purchaser ('{ticket_purchaser}')</option>
</select>

Here's the jQuery I attempted to use

$('select option:contains("{ticket_holder}")').text().replace("{ticket_holder}","Test");

Which failed to process.

Upvotes: 0

Views: 66

Answers (2)

Oleksii Aza
Oleksii Aza

Reputation: 5398

Try something like this:

var element = $('select option:contains("{ticket_holder}")');
var text = element.text();
element.text(text. replace("{ticket_holder}","Test"));
  1. For assigning text to element you need to pass text into .text() function.
  2. .replace() returns changed text, but doesn't change original.

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108482

$.fn.text also takes a function as argument, useful when you want to manipulate the contents:

$('select option:contains("{ticket_holder}")').text(function() {
    return $(this).text().replace(/{ticket_holder}/, 'Test');
});

Upvotes: 0

Related Questions