<html>
<head></head>
<body>
<select class="flex_select">
<option value="con_1">One</option>
<option value="con_2" selected="selected">Two</option>
<option value="con_3">Three</option>
</select>
<div class="flex_parent"></div>
<script>
var select = document.querySelector('select') // use more specific selector here
var classTwo = document.querySelector('.flex_parent')
function checkSelect () {
if (event.target.value === 'con_2') {
classTwo.classList.add('flex_parent_2')
}else if (event.target.value === 'con_3') {
classTwo.classList.add('flex_parent_3')
}else if (event.target.value === 'con_1') {
classTwo.classList.remove('flex_parent_3', 'flex_parent_2')
}
}
select.addEventListener('change', checkSelect);
</script>
</body>
</html>
This code works.
If that doesnât work, youâve got a collision somewhere else in your code, or youâve put your script tag above your HTML elements, causing them to not exist when you try and target the elements.
The problem is that the drop drowns is working, and the second condition is also getting selected, but when the page load the class that should be injected when the second condition is true is not getting inserted.
however If I select condition 3 and then select condition 2then it gets injected.
I tried this:
var defult_id='con_2';
document.getElementById(defult_id).selected = "true";
If youâre going to set the second element as the initial state, start your div with the âflex_parent_2â class already applied, rather than expecting Javascript to do it.
<div class='flex_parent flex_parent_2'>
The reason the code fails to run on page load is that your code is looking for event.target - if you just call the function rather than it being triggered by an event, event.trigger doesnt exist (event doesnt exist at all.)
Well, two solutions - one, put the initial class into the div element as i stated, and DONT run the code on load - it doesnt need to be run, the div already has the class it should have.
The other solution is to rewrite the function to be event-neutral, and instead target the select box by its selector (which youâve already defined as âselectâ), so instead of event.target.value, it would be select.value.
Using event.target makes the code more flexible - if you wanted to put it onto multiple dropdowns on the same page, for example.