我对javascript很新。我阅读此链接并尝试自定义但不起作用:Disable an input field if second input field is filled
我想让人们在两个选项之间切换 - 城市和邮政编码。我想启用他们最后选择的任何字段并禁用另一个字段。例如,如果它们位于邮政编码选项卡上并按下提交按钮,则提交邮政编码中的任何输入都会被提交,而不是城市&反之亦然。
html是:
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
脚本是:
var dis1 = document.getElementById("city");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("zipcode").disabled = true;
}
}
var dis2 = document.getElementById("zipcode");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("city").disabled = true;
}
}
非常感谢任何帮助!该网站为http://austinhometeam.staging.wpengine.com/joyce-newsletter/
答案 0 :(得分:0)
就像我在评论中告诉你的那样,你需要更改“getElementById”中的ID。
当另一个字段为空时,我还添加了重新启用的字段。
我在select中添加一个空值,当选择null时,邮政编码的字段返回启用。
<强> HTML 强>
<ul class="tabs">
<li><a class="border-radius top med" href="#city">City</a></li>
<li><a class="border-radius top med" href="#zipcode">Zipcode</a></li>
</ul>
<div id="city"><label class="IDX-advancedText">City</label>
<select id="aht-home-city" name="city[]" class="IDX-select " autocomplete="off">
<option value=""></option>
<option value="2115">Austin</option>
<option value="2718">Bartlett</option>
</select>
</div>
<div id="zipcode"><label class="IDX-advancedText">Zipcode</label>
<input class="IDX-advancedBox IDX-advWildText" id="IDX-aw_zipcode" type="text"
maxlength="255" name="aw_zipcode" value="" /></div>
Javascript:
var dis1 = document.getElementById("aht-home-city");
var dis2 = document.getElementById("IDX-aw_zipcode");
dis1.onchange = function () {
if (dis1.value !== "" || dis1.value.length > 0) {
dis2.disabled = true;
} else {
dis2.disabled = false;
}
};
dis2.onchange = function () {
if (dis2.value !== "" || dis2.value.length > 0) {
dis1.disabled = true;
} else {
dis1.disabled = false;
}
};
有一个有效的例子: JSBin Example
答案 1 :(得分:0)
正在寻找类似这样的行为?
var last = "";
var dis1 = document.getElementById("aht-home-city");
dis1.onchange = function () {
last = "city";
document.getElementById("IDX-aw_zipcode").disabled = true;
}
var dis2 = document.getElementById("IDX-aw_zipcode");
dis2.onchange = function () {
last = "zipcode";
if (this.value != "" || this.value.length > 0) {
document.getElementById("aht-home-city").disabled = true;
}
}
选中 jsFiddle
注意:HTML中还缺少</select>
标记。