Question

I'm trying to change the text of a group of select options when a particular option is selected from a previous dropdown.

Here is my html:

<select class="select" id="eventType" name="eventType" size="1">
    <option value="0"></option>
    <option value="wedding" name="wedding">Wedding</option>
    <option value="private_party" name="private_party">Private Party</option>
    <option value="corporate" name="corporate">Corporate Event</option>
 </select>

<select class="select" id="band_type_choices" name="bandType">
<option value="0"></option>
    <option value="acoustic" class="acoustic" name="acoustic">Acoustic</option>
    <option value="jazz" class="jazz" name="jazz">Jazz/Easy Listening</option>
    <option value="acoustic_jazz" class="acoustic_jazz" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option> 
    <option value="party" class="party" name="party">Party</option>
    <option value="acoustic_party" class="acoustic_party" name="acoustic_party">Acoustic + Party</option> 
    <option value="jazz_party" class="jazz_party" name="jazz_party">Jazz/Easy Listening + Party</option> 
    <option value="acoustic_jazz_party" class="acoustic_jazz_party" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option> 
 </select>

When someone selects "Wedding" from the first drop down, I want to change the text of all the #band_type_choices dropdown

Here is the jQuery i'm using so far, but it does nothing:

$('#eventType').change(function() {
    var eventTypeName = $("#eventType option:selected");

if (eventTypeName.is(".wedding") ) {
    $('#band_type_choices option:contains("acoustic")').text('Wedding Ceremony');
}

});
Was it helpful?

Solution

Your selectors are messed up

$('#eventType').change(function() {
    var eventTypeName = $("#eventType option:selected");

    if (eventTypeName.is('[name="wedding"]') ) {
        $('#band_type_choices option[name="acoustic"]').text('Wedding Ceremony');
    }

});

The wedding option does not have a class wedding, it has name attribute set as wedding, also the :contains is case sensitive so it will be better to use a name selector for setting the value

Demo: Fiddle

OTHER TIPS

Firstly, you can get the selected value of a select using val() (or value natively). Secondly, none of the options have the class wedding so is('.wedding') will always fail. Finally, :contains is case-sensitive, so you'd need Acoustic. Try this:

$('#eventType').change(function() {
    if (this.value == "wedding") {
        $('#band_type_choices option:contains("Acoustic")').text('Wedding Ceremony');
    }
});

Example fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top