.val("value") not working as expected in jQuery 1.5

I'm using jQuery 1.5.2 to manipulate 2 dropdown selects on a form. I have a special requirement that if the 'Other' option is selected, both selects must be 'Other'.

Problem:

my code looks like this

$("#Select_One")
    .change(function() {
        if($(this).val() == "Other") {
            $("#Select_Two").val("Other");
        }
        else {
            if($("#Select_Two").val() == "Other") {
                $("#Select_Two").val("");
            }
        }
    });

$("#Select_Two")
    .change(function() {
        if($(this).val() == "Other") {
            $("#Select_One").val("Other");
        }
        else {
            if($("#Select_One").val() == "Other") {
                $("#Select_One").val("");
            }
        }
    });

The problem is that, rather than enforcing the rule that both fields be 'Other', $("#Select_Two").val("Other"); just adds or overwrites with the value="Other" property on each <option> under #Select_Two. Same thing happens with #Select_One.

My HTML is from a grails template

    <g:select id="Select_One"
              name="Units_One"
              class="Required DropDown"
              from="${Unit_One.values()}"
              optionKey="value_"
              optionValue="${{it.value_}}"
              noSelection="${['': message(code: 'units.no.selection')]}"
     />
     <g:select id="Select_Two"
               name="Units_Two"
               class="Required DropDown"
               from="${Unit_Two.values()}"
               optionKey="value_"
               optionValue="${{it.value_}}"
               noSelection="${['': message(code: 'units.no.selection')]}"
     />

What chrome debugger shows me after setting ether field to 'Other' is this...

<select name="Units_Two" id='Select_Two" class="Required DropDown">
  <option value="Other">Select Number</option>
  <option value="Other">Other</option>
  <option value="Other">1</option>
  etc...

The else clause of these functions works just as intended.


Question:

How do I enforce that selecting 'Other' in one field automatically selects 'Other' in the corresponding field?

Answers


Maybe try:

$("#Select_One").change(function() {
    if ($(this).val() == "Other") {
        $("#Select_Two option[value='Other']").attr("selected",true);
    }
    else {
        if ($("#Select_Two").val() == "Other") {
            $("#Select_Two").val("");
        }
    }
});

$("#Select_Two").change(function() {
    if ($(this).val() == "Other") {
        $("#Select_One option[value='Other']").attr("selected",true);
    }
    else {
        if ($("#Select_One").val() == "Other") {
            $("#Select_One").val("");
        }
    }
});‚Äč

Need Your Help

How to export a variable from a module in JavaScript?

javascript node.js variables module

According to this post we know that variables can be exported from one module in JavaScript: