If value in select option is lower than in second select option, then change option

时间:2018-03-25 20:33:29

标签: javascript jquery if-statement

I want to achieve:

If I select "16" in first select box and bigger value in second, for example "17", then in second select automatically changing to "16".

Just if value in first select box is lower than second, always change to same values, for example 16 to 16, 18 to 18.

<select id="from_age_js" name="from_age" class="select-advertise-style">
   <option value="f13">13</option>
   <option value="f14">14</option>
   <option value="f15">15</option>
   <option value="f16">16</option>
   <option value="f17">17</option>
   <option value="f18" selected>18</option>
   <option value="f19">19</option>
   <option value="f20">20</option>
</select>
—
<select id="to_age_js" name="to_age" class="select-advertise-style">
   <option value="t13">13</option>
   <option value="t14">14</option>
   <option value="t15">15</option>
   <option value="t16">16</option>
   <option value="t17">17</option>
   <option value="t18">18</option>
   <option value="t20" selected>20+</option>
</select>

1 个答案:

答案 0 :(得分:1)

That's an easy one, in your case, with pure javascript, I would do something like this:

function checkit()
{

//Store the two dropdowns for easy reference
var fromAge = document.getElementById('from_age_js');
var toAge = document.getElementById('to_age_js');

//Verify if the toAge value is minor, to see if the conditional code will be executed
if( fromAge.options[fromAge.selectedIndex].value > 
        toAge.options[toAge.selectedIndex].value)
    {
        //In that case, match the values to be the same...
        document.getElementById('to_age_js').value =
      fromAge.options[fromAge.selectedIndex].value;
    }

}

And you just have to add that function to where you want it to be called. I would choose to add the onchange event from Javascript within the select dropdowns. Like this:

<select id="from_age_js" name="from_age" class="select-advertise-style" onchange="checkit();">

You can see a working example here:

https://jsfiddle.net/8cmad3tz/19/

相关问题