简体   繁体   中英

Change option values of select 2 if select 1 has a value with jquery

I require a bit of jQuery to do the following:

A user can currently select Program and/or a region.

If a user selects Program AND a Region I require the option values of the region dropdown to change to "?region=1" and "?region=2"

<select class="program" id="program">
            <option value="program1.html">Program 1</option>
            <option value="program2.html">Program 2</option>
</select>

<select class="region" id="region">
            <option value="region1.html">Region 1</option>
            <option value="region2.html">Region2</option>
</select>

Greatly appreciate the assist.

My attempt at JQuery:

$('#program').on('change', function () { if($(this).val() !="0") { } else { // no option is selected } })

You need to further extend the change event for #program and include a similar one for #region .

 var programSelected = null; var regionSelected = null; $('#program').on('change', function(element) { programSelected = $('#program option:selected').text(); updateRegionOptions(); }); $('#region').on('change', function(element) { regionSelected = $('#region option:selected').text(); updateRegionOptions(); }); function updateRegionOptions() { if(programSelected != null && regionSelected != null) { $('#region option').each(function() { var modifiedString = '?'; modifiedString += $(this).val().replace(/\\d+/,''); modifiedString = modifiedString.replace('.html',''); modifiedString += '='; modifiedString += $(this).val().match(/\\d+/); $(this).val(modifiedString); }); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select class="program" id="program"> <option value="" selected disabled>Select Program</option> <option value="program1.html">Program 1</option> <option value="program2.html">Program 2</option> </select> <select class="region" id="region"> <option value="" selected disabled>Select Region</option> <option value="region1.html">Region 1</option> <option value="region2.html">Region2</option> </select>

Explanation of the logic above:

  1. on('change' event for both #region and #program
  2. Set the relevant variable programSelected or regionSelected depending on the change event
  3. Run function updateRegionOptions();
  4. If the variables programSelected and regionSelected both have a value
  5. For each of the options in #region
  6. Mutate the existing value to be of the form "?region=1" and "?region=2"
  7. Update the value section of each of the option elements to have this value

The relevant JSFiddle for review.

If this solved your issue, please accept this answer :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM