在Dropbox中更改选项时更改div的可见性

时间:2016-04-06 08:36:38

标签: javascript html

我的php中有这样的代码:

<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type: 
<select name="customerType">
    <option value="">Customer Type?</option>
    <option value="ret">Customer</option>
    <option value="trd">Trade</option>
</select>

这些是必须根据所选选项更改可见性的div:

<div id="retCustDetails" class="custDetails">
    Forename <input type="text" name="forename" id="forename" />
    Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
    Company Name <input type="text" name="companyName" id="companyName" />
</div>

我试过这个javascript:

<script>
document.getElementsByName("customerType").onchange = function () {
    var val = this.options[this.selectedIndex].value;
    document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
    document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
</script>

但div tradecustdetails"没有出现,div retCustDetails仍在那里。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

getElementsByName()返回具有指定名称的文档中所有元素的集合。因此你必须像这样循环它们:

var x = document.getElementsByName("customerType");
for (var i = 0; i < x.length; i++) {
    // do something with x[i]
}

如果您只使用一个select元素,那么最好像这样使用getElementById()

<强> HTML

<select id="customerType" name="customerType">
    <option value="">Customer Type?</option>
    <option value="ret">Customer</option>
    <option value="trd">Trade</option>
</select>

<强>脚本

document.getElementById("customerType").onchange = function () {
    var val = this.options[this.selectedIndex].value;
    document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
    document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};

答案 1 :(得分:1)

更新了您的脚本,这应该可行。

<script>
     function jsFunction() {
         var val =  document.getElementById("dropSelect").options[document.getElementById("dropSelect").selectedIndex].value;
         document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
         document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
     }
</script>

同时更新您的下拉列表HTML。

<select id="dropSelect" name="customerType" onchange="jsFunction()">

编辑#1:使用getElementsByName()

function jsFunction() {
     var val =  document.getElementsByName("customerType")[0];
     val = val.options[val.selectedIndex].value;                    
     document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
     document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
}