Currently I have 2 dropdown boxes with the same options. These options are all filled from the backend. Now I want it so that whenever I choose 1 option in the dropdown box, the other dropdown also automatically chooses the same value and this works both ways. The following is my dropdown box code:
<select name="lead_status" id="leadstatus" class="form-control">
<option value="">Select</option>
<?php foreach($leadstatus as $key => $status): ?>
<option value="<?php echo $key; ?>" <?php echo $key==$lead->lead_status?'selected="selected"':'' ?>><?php echo $status; ?></option>
<?php endforeach; ?>
</select>
<select name="lead_status" id="leadstatus2" class="form-control">
<option value="">Select</option>
<?php foreach($leadstatus as $key => $status): ?>
<option value="<?php echo $key; ?>" <?php echo $key==$lead->lead_status?'selected="selected"':'' ?>><?php echo $status; ?></option>
<?php endforeach; ?>
</select>
I've tried creating a function for onclick where it creates a check saying:
if (document.getElementById('leadstatus').value == '1')
document.getElementById("leadstatus2").value = '1';
But this wont work since I have a lot of data in the dropdown lists and it is dynamic.
Since the question mentions... ...the other dropdown also automatically chooses the same value and this works both ways...
Try the following, ..
const leadStatusList = document.getElementById('leadstatus');
const leadStatus2List = document.getElementById('leadstatus2');
const setDropdownValue = (event) => {
leadStatusList.value = event.target.value;
leadStatus2List.value = event.target.value;
}
leadStatusList.onchange = setDropdownValue;
leadStatus2List.onchange = setDropdownValue;
Simply set the second dropdown's selectedIndex property to that of the first dropdown:
let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
box1.addEventListener("change", () => {
box2.selectedIndex = box1.selectedIndex;
});
box2.addEventListener("change", () => {
box1.selectedIndex = box2.selectedIndex;
});
<select id="box1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
<select id="box2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>