如何在javascript中禁用文本字段和组合框

时间:2014-03-27 05:43:18

标签: javascript html combobox

我在使用另一个组合框禁用文本框和组合框时出现问题是我的javascript到目前为止:

 category.onchange = function () {
 var val = this.options[this.selectedIndex].value;   
 document.getElementById("bos").disabled = (val == "Military","Civilian") ? true : false;
 document.getElementById("afpsn").disabled = (val ==  "Dependent","Civilian") ? true : false;
};

这是我的HTML:

<select name="category" size="1" id="category">
  <option selected="selected">Choose...</option>
  <option value="Civilian">Civilian</option>
  <option value="Military">Military</option>
  <option value="Dependent">Dependent</option>
            </select>

  <select name="bos" id="bos" >
  <option value="">Branch of Service</option>
  <option value="PAF">PAF</option>
  <option value="PA">PA</option>
  <option value="PN">PN</option>
  <option value="TAS">TAS</option>
</select>

  <input id = "afpsn"  name="afpsn" type="text" id="afpsn" size="38" placeholder="AFPSN" />

它应该是每当我选择依赖或民用时,其他组合框和文本字段将被禁用,并且当我选择军事时将启用。请帮忙!

4 个答案:

答案 0 :(得分:0)

请改为尝试:

您的情况(与strings比较)不正确。

example

category.onchange = function () {
    var val = this.options[this.selectedIndex].value;
    document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
    document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
};

修改

要在页面加载时附加事件(假设您没有使用jQuery),一种方法是将其附加到pageload上,如:

function init() {
    category.onchange = function () {
        var val = this.options[this.selectedIndex].value;
        document.getElementById("bos").disabled = (val === "Military" || val === "Civilian") ? true : false;
        document.getElementById("afpsn").disabled = (val === "Dependent" || val === "Civilian") ? true : false;
    };
}

以及<body>

上的类似内容
<body onload="init();">
   ...
</body>

该示例有效的原因是jsfiddle.net默认情况下加载js框中的函数。但在您的情况下,您必须手动执行此操作。

答案 1 :(得分:0)

我不认为有(val == "Military","Civilian")之类的东西  You can try this Fiddle

答案 2 :(得分:0)

尝试以下代码:

/*Function to check if value is in an array*/
function isInArray(value, array) {
  return array.indexOf(value) > -1;
}
/*******************************************/

var s=document.getElementById("elementId");
s.disabled = isInArray(s.value,["Military","Civilian"]); //Function automatically returns "true" or "false" depending on value

Demo Fiddle

答案 3 :(得分:0)

This fiddle会帮助你。你也可以编辑逻辑。

category.onchange = function () {
 var val = this.options[this.selectedIndex].value; 
  //  alert(val);
 document.getElementById("bos").disabled = (val === "Military") ? false : true;
    document.getElementById("afpsn").disabled = (val === "Military") ? false : true;
 document.getElementById("afpsn").disabled = (val ===  "Dependent" || val ===  "Civilian" ) ? true : false;
 document.getElementById("bos").disabled = (val ===  "Dependent" || val ===  "Civilian" ) ? true : false;
};