How do I disable input field when certain select list value is picked

混江龙づ霸主 提交于 2019-12-13 04:56:58

问题


How do I disable and make the input field text to hidden when certain value is selected from select list? In my code, I need to disable and make the input text to hidden when "United States" is selected from my drop down.

My HTML: JSFiddle Link

My Javascript:

document.getElementById('BillingCountryCode').onchange = function () {
    if(this.value != '840') {
        document.getElementById("BillingStateProvince").disabled = true;
        document.getElementById("BillingStateProvince").style.display="none"
    } else {
        document.getElementById("BillingStateProvince").disabled = false;
        document.getElementById("BillingStateProvince").style.display="block"
    }
}

回答1:


The problem with your fiddle is you have two elements with the same ID. You can do exactly what is already there, just change the ID on either the state dropdown or the text input. Updated code might look like this, if you simply name the text input the same with a 2:

document.getElementById('BillingCountryCode').onchange = function () {
    if(this.value != '840') {
        document.getElementById("BillingStateProvince").disabled = true;
        document.getElementById("BillingStateProvince").style.display="none";
        document.getElementById("BillingStateProvince2").disabled = false;
        document.getElementById("BillingStateProvince2").style.display="block";
    }

    else {
        document.getElementById("BillingStateProvince").disabled = false;
        document.getElementById("BillingStateProvince").style.display="block";
        document.getElementById("BillingStateProvince2").disabled = true;
        document.getElementById("BillingStateProvince2").style.display="none";
    }
}



回答2:


If i got the question , simply invert the if condition like this :

if(this.value === "840") { ... } 

here is the working fiddle : http://jsfiddle.net/antwonlee/cf4Sz/7/



来源:https://stackoverflow.com/questions/16547929/how-do-i-disable-input-field-when-certain-select-list-value-is-picked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!