Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change text of an option when another option is selected

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');
    }
});
like image 581
Sam Skirrow Avatar asked Dec 01 '22 18:12

Sam Skirrow


1 Answers

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

like image 124
Arun P Johny Avatar answered Dec 22 '22 20:12

Arun P Johny