EN VI

Javascript - Select2 - Set val IF selected option == "Apple"?

2024-03-15 04:30:06
How to Javascript - Select2 - Set val IF selected option == "Apple"

I have a select2 drop down and would like to know the best way to SET a VALUE if the OPTION selected == " Apple" for instance.

Here is my Select2

<select id="fruit" title="fruit" name="fruit"
                                      class="form-control select2-single">
                                  <option value="">&nbsp;</option>
                                  <option value="">Apple</option>
                                  <option value="">Lemon</option>
                              </select>

What I'd like to achieve is:

If Option "Apple" is selected, SET Value to THISVARIABLE (I get responses from an AJAX Post and would like to dynamically set the Value

Solution:

This small example might give you something to study.

The first select is like your AJAX, and it sets a variable. It then uses that variable to set the value of a second drop-down.

Note: To set the value of a Select/dropdown, set the value of the Select element to be the value of the desired option. Thus, every option should have a "value".

let theVar;

const leSelect = document.querySelector('#fruit')
leSelect.addEventListener('change', handle_sel_change);

function handle_sel_change(e){
   const leComp = document.querySelector('#computer');
   theVar = leSelect.value;

   leComp.style.display = 'block';
   leComp.value = theVar;
}
body{display:flex;}
#computer {display: none; margin-left:20px; }
<select id="fruit">
    <option value="">&nbsp;</option>
    <option value="epple">Apple</option>
    <option value="remon">Lemon</option>
</select>

<select id="computer">
    <option value="">&nbsp;</option>
    <option value="epple">Apple</option>
    <option value="remon">Microsoft</option>
</select>

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login