2014-04-18 147 views
1

我希望以下函數顯示不同的html輸入取決於用戶選擇哪種類型的用戶。Javascript - onchange函數只能使用一次(第一次更改後)與html選擇

(選擇第一個選項時)下面的代碼只運行一次

這是我的html:

<select name="customerType" id="customerType" onchange="return customerTypeFunction()"> 
    <option value="">Customer Type?</option> 
    <option value="nonCorp">Customer</option> 
    <option value="corp">Corporate</option> 
</select> 

<div id="nonCorpCustDetails" class="custDetails"> 
    Forename <input type="text" name="forename" id="forename"/> 
    Surname <input type="text" name="surname" id="surname"/> 
</div> 

<div id="corporateCustDetails" class="custDetails" style="visibility:hidden"> 
    Company Name <input type="text" name="companyName" id="companyName"/> 
</div> 

這是我的javascript函數:

function customerTypeFunction() { 

    var customerTypeSelect = document.getElementById("customerType").value; 

    var corpCustomer = document.getElementById("corporateCustDetails"); 
    var nonCorpCustomer = document.getElementById("nonCorpCustDetails"); 

    if (customerTypeSelect = 'nonCorp') { 

     corpCustomer.style.visibility = "hidden"; 
     nonCorpCustomer.style.visibility = "visible"; 

    } 

    if (customerTypeSelect = 'corp') { 

     corpCustomer.style.visibility = "visible"; 
     nonCorpCustomer.style.visibility = "hidden"; 

    } 

} 

回答

4

=是分配,==/===是比較。改變你的if語句以反映這一點。

if (customerTypeSelect === 'nonCorp') {  
    corpCustomer.style.visibility = "hidden"; 
    nonCorpCustomer.style.visibility = "visible";  
} 

if (customerTypeSelect === 'corp') { 
    corpCustomer.style.visibility = "visible"; 
    nonCorpCustomer.style.visibility = "hidden"; 
} 

jsFiddle here