Javascript - onchange函数只能使用html select一次(在第一次更改后)

时间:2014-04-18 16:47:07

标签: javascript

我希望以下函数显示不同的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";

    }

}

1 个答案:

答案 0 :(得分: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