简体   繁体   中英

Show/hide depending on dropdown menu selection

So I have a dropdown menu. The id for this dropdown menu is "courses". This dropdown also has an additional attribute, onclick="displayField();

The dropdown has 2 options.

2 and 3.

Now, I want everything with the class rsform-block-cotecours1 to be hidden depending on which option is chosen.

Here is the JavaScript for that:

function displayField()
{
  if(document.getElementById("courses").text == '2';)
  document.getElementsByClassName('rsform-block-cotecours1').style.display="none";

  if(document.getElementById("courses").text == '3';)
  document.getElementsByClassName('rsform-block-cotecours1').style.display="";
}


window.addEvent('domready', function() {
displayField();
});

However, this doesn't work, and I don't know why.

Is this what you are looking for?

Fiddle: fiddle

<select id="courses" onchange="ddlChange()">
  <option value="2">2</option>
  <option value="3">3</option>
 </select>

JavaScript

function ddlChange() {

    if (document.getElementById("courses").value =="2"){
      document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";
        alert(document.getElementById("courses").value );
    }     
     if (document.getElementById("courses").value == "3"){
      document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="block";
         alert(document.getElementById("courses").value );
    }     
}

Change the code to following and test

function displayField()
{
  if(document.getElementById("courses").value == '2';)
  document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";

  if(document.getElementById("courses").value == '3';)
  document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="";
}


window.addEvent('domready', function() {
displayField();
});

in case you want to access the ext and not the value of dropdown list in javascript, then use following code to access the text of selected option from drop down

var courseElement = document.getElementById("courses");
var text = "";
if (courseElement.selectedIndex != -1)
{
    text = courseElement.options[courseElement.selectedIndex].text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM