最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Running javascript function when option selected - Stack Overflow

programmeradmin4浏览0评论

I want to execute a function depending on which option in a dropdown menu is selected. For now I just wrote document.write() function to test if anything is happening.

However, nothing is printing, and the code is not working as I wanted.

<h>Would you like to see count values per hour or minute?</h><br>
<Select id="Selector">
   <option value="hr">Hour</option>
   <option value="min">Minute</option>
</Select>
<script>
  if (document.getElementById('Selector').value == "min") {
    document.write("Hello World!");
  }

</script>

I want to execute a function depending on which option in a dropdown menu is selected. For now I just wrote document.write() function to test if anything is happening.

However, nothing is printing, and the code is not working as I wanted.

<h>Would you like to see count values per hour or minute?</h><br>
<Select id="Selector">
   <option value="hr">Hour</option>
   <option value="min">Minute</option>
</Select>
<script>
  if (document.getElementById('Selector').value == "min") {
    document.write("Hello World!");
  }

</script>

Share Improve this question asked Aug 7, 2018 at 20:56 MelanieMelanie 3173 gold badges8 silver badges17 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

For this, you will need an onchange listener, so every time the user changes the value on the select, it call that listener function and do something that you need. In my example below, I just change the document background, but it is sufficient to you get the logic, right?

<h>Would you like to see count values per hour or minute?</h><br>
<Select id="Selector">
   <option value="hr">Hour</option>
   <option value="min">Minute</option>
</Select>
<script>
  document.getElementById("Selector").onchange = changeListener;
  
  function changeListener(){
  var value = this.value
    console.log(value);
    
    if (value == "min"){
      document.body.style.background = "red";
    }else if (value == "hr"){
      document.body.style.background = "blue";
    }
    
  }

</script>

NOTE: onchange is only triggered when the value changes, if the same value is selected, it doesn't trigger, so the function won't be called. To avoid this, take a look about other listeners, such as onclick or onfocus or onblur

you can use onchange event to refer your function on selection like

<Select id="Selector" onchange="myFunction()">


function myFunction() {
   var x = document.getElementById("Selector").value;
   if(x==='min')
   document.write("Hello World!");
}

You need to attach onchange event listener to your select element. http://jsfiddle/gj2n6rux/2/

发布评论

评论列表(0)

  1. 暂无评论