HTML select dropdownlist with javascript function

2019-06-12 16:12发布

问题:

This is how far I got:

<head>
<script type="text/javascript">
function showonlyone(thechosenone) {
    var article = document.getElementsByTagName("div");
    for(var x=0; x<article.length; x++) {
        name = article[x].getAttribute("name");
        if (name == 'article') {
            if (article[x].id == thechosenone) {
                article[x].style.display = 'block';
            }
            else {
                article[x].style.display = 'none';
            }
        }
    }
}
</script>
</head>
<form>
<select>
<option SELECTED>Choose one</option>
<option value="javascript:showonlyone(id1)">First</option> <!-- That's probably wrong -->
<option value="javascript:showonlyone(id2)">Second</option>
</select>
</form>
<div name="article" id="id1" style="display:none;">
First one selected
</div>
<div name="article" id="id2" style="display:none;">
Second one selected
</div>

Here is what it should do:

  • Create a dropdownlist (with 3 Values)

  • If you click on "First" it should only show the of the content of <div id="id1">

  • If you click on "Second" it should only show the of the content of <div id="id2">

I know that this can't work like this. But I do not know how I can get this working. There might be a easier way than this javascript function but it has to be this way.

Thank you for your help

回答1:

Use a onchange event handler instead:

  • Update your <select> to <select onchange="showonlyone(this)">.
  • Change your <option> values to only the IDs - not JavaScript calls.
  • Update your JavaScript to accept the HTMLSelectElement (which will be passed-in by the this, above). (Yes, you were correct here.)
  • From the chosen HTMLSelectElement, ask it for its value.

Here is a fixed, working version: http://jsfiddle.net/YRF6u/

Also included here:

<head>
  <script type="text/javascript">
    function showonlyone(selector) {
      var thechosenone = selector.value;
      var article = document.getElementsByTagName("div");
      for(var x=0; x<article.length; x++) {
        name = article[x].getAttribute("name");
        if (name == 'article') {
          if (article[x].id == thechosenone) {
            article[x].style.display = 'block';
          }else{
            article[x].style.display = 'none';
          }
        }
      }
    }
  </script>
</head>
<form>
  <select onchange="showonlyone(this)">
    <option SELECTED>Choose one</option>
    <option value="id1">First</option>
    <option value="id2">Second</option>
  </select>
</form>
<div name="article" id="id1" style="display:none;">
  First one selected
</div>
<div name="article" id="id2" style="display:none;">
  Second one selected
</div>

I would not consider this production-ready code, but it should be sufficient enough to solve your current round of questions.