0

I have multiple dropdown selections on a single page with exact same options but different IDs. I need dropdown A and B to have the same option selected at all times but only if they both share those options.

I'm a javascript noob so I've tried many variations of code but nothing works, I think it's best if someone could write this simple code from scratch.

Imagine these two selections with cloned options:

<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>

<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>

If you select red in ID california it needs to switch to red in ID texas, and vice versa.

Vlad
  • 31
  • 1
  • 5
  • Use a common class on the ones that have same options. Simplifies any logic needed....just loop through that class – charlietfl Aug 06 '19 at 12:17
  • 1
    The basic idea is to add an `onchange` handler to A that sets B to the same `.value` and vice versa. Add your attempt to the question, ideally as a [mre]; stackoverflow isn't a free code writing service. –  Aug 06 '19 at 12:19
  • What have you tried already? Are you familiar with jquery? You can get the value of a select with `$('select').val()` and set it with, for example, `$('#texas').val('blue');` – TKoL Aug 06 '19 at 12:19
  • refer to this question it may help you https://stackoverflow.com/questions/19728666/drop-down-box-dependent-on-the-option-selected-in-another-drop-down-box – jagadish N Aug 06 '19 at 12:24
  • If you have a option to use Jquey you can use my solution below..If at all you are not looking for a pure JavaScript solution – too_cool Aug 06 '19 at 12:26

5 Answers5

0

You can add a common class and select on the change event something like following

Jquery

 $(document).ready(function(){ 
  $(".select").change(function() {   
    $(".select").not(this).find("option[value="+ $(this).val() + "]").attr('selected', true)
  }); 
});

Pure JavaScript Solution as already written by @Emeeus

const selectElement = [...document.getElementsByClassName("ClassName")];

selectElement.forEach(a => {
  a.addEventListener("change", (e) => {
    selectElement.forEach(aa => {
      if (aa.querySelectorAll(`option[value=${e.target.value}]`).length)
        aa.value = e.target.value;
    })
  })
})
too_cool
  • 1,164
  • 8
  • 24
  • Question isn't tagged jQuery – charlietfl Aug 06 '19 at 12:21
  • Thank you! I've tried both javascript and jquery and they both work! However, I did not mention that I need these dropdowns for PayPal, and pp passes product name through the select value and so inevitably it has spaces, e.g. "Brown Bag - $1,000". As soon as there are spaces or commas within the option value, it stops working.. In fact none of the given solutions work if there's a space (i.e. more than one word) in the option value. Is there anything to fix this? Thank you! – Vlad Aug 06 '19 at 14:52
0

The ideal solution would be using classes, but with that HTML here a solution:

const selects = [...document.getElementsByTagName("select")];

selects.forEach(s => {
  s.addEventListener("change", (e) => {
    selects.forEach(sl => {
      if (sl.querySelectorAll(`option[value=${e.target.value}]`).length)
        sl.value = e.target.value;
    })
  })
})
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>

<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>

<select id="las_vegas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
Emeeus
  • 5,072
  • 2
  • 25
  • 37
0

A simple way to get this done is :

  • reference the select elements in JavaScript and store the two of them in an array.

    • when looping through the selects we can store the index of the current select, that has to be used to get the other select (a simple mathematical calculation).
  • loop through that array (that means looping through the selects) and attach a change event listener to each one of the select elements.

  • fetch the option that has to be selected, if found, after filtering the options of the other select based on the value of the selected option.
  • if there's an option that has the same value as the selected option, select that option in the other select.

This may still a bit ambiguous, a demo is worth a hundred docs :

the next demo takes into consideration that an/some option(s) may not appear in both of the select elements, simply nothing will happen and the same functionality stays as is.

/** an array that stores the selects **/
const selects = [document.getElementById('california'), document.getElementById('texas')];

/** ## cycle through these selects
* el: current select in the loop.
* idx: its index in the "selects" array. 
**/
selects.forEach((el, idx) => {
  /** attach change listener **/
  el.addEventListener('change', () => {
    /** get the option that should be selected in the other select if found there **/
    /** "selects[Math.abs(idx - 1)]" gets the other select (the one that isn't changed) **/
    const toBeSelected = [...selects[Math.abs(idx - 1)].options].filter(o => o.value === el.options[el.selectedIndex].value);
    /** if we have an option from the other select's options that has the same value as the selected one then return in order to be selected **/

    /** if ther's an option that matches the above condition simply select it **/
    toBeSelected[0] && (selects[Math.abs(idx - 1)].selectedIndex = toBeSelected[0].index);
  });
});
<select id="california">
  <option value="red">red</option>
  <option value="yellow">yellow</option>
  <option value="blue">blue</option>
</select>

<select id="texas">
  <option value="red">red</option>
  <option value="yellow">yellow</option>
  <option value="blue">blue</option>
  <!-- new option that doesn't exist in the other select element -->
  <option value="green">green</option>
</select>
ThS
  • 4,597
  • 2
  • 15
  • 27
0

this is very simple code :

<select id="california" onclick="applyEvent()">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="blue">blue</option>
    <option value="brown">brown</option>
</select>

<select id="texas" onclick="apply_Event()">
    <option value="red"">red</option>
    <option value="yellow">yellow</option>
    <option value="blue">blue</option>
    <option value="brown">brown</option>
</select>
<script type="text/javascript">
    function applyEvent() {
        document.getElementById("texas").value = document.getElementById('california').value;
    }
    function apply_Event() {
        document.getElementById("california").value = document.getElementById('texas').value;
    }
</script>
milad
  • 7
  • 1
  • 6
-1
<select id="california">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="blue">blue</option>
</select>

<select id="texas">
    <option value="red">red</option>
    <option value="yellow">yellow</option>
    <option value="blue">blue</option>
</select>

<script>
var californiaSelect = document.getElementById('california');
var texasSelect = document.getElementById('texas');

californiaSelect.addEventListener('change', () => {
    texasSelect.value = californiaSelect.value;
})
texasSelect.addEventListener('change', () => {
    californiaSelect.value = texasSelect.value;
})
</script>

You can find a working example is this fiddle

getElementById

addEventListener

Morphyish
  • 3,932
  • 8
  • 26