Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run a javascript function when selecting a specific selection?

I am thinking of running a javascript function when selecting a specific selection, such as:

<select name="fruit">
<option value="1">orange</option>
<option value="2">apple</option>
<option value="3">banana</option>
</select>

And if I select "orange", a orange picture will pop out like:

function department() {
    let form = document.basic;
    let choice = form.fruit.value;
    if (choice === 1) {
        document.getElementById("orange_img").style.display = "inherit";
    }
}

How can I get this javascript work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS: Is there methods without jquery?

>Solution :

You can add eventListener to onchange event, check the value, and add custom logic to handle it. No need of jquery!

const fruitSelect = document.getElementById('fruit');
fruitSelect.addEventListener('change', (e) => {
  const value = e.target.value;
  if(value === '1') { // corresponds to orange
   // do stuff here
  }
});
<select name="fruit" id="fruit">
<option value="1">orange</option>
<option value="2">apple</option>
<option value="3">banana</option>
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading