小弟最近在學習網頁前端,最近遇到一個範例,當選擇選項1時,input1會disable,以此類推,最後的選項則全部不受限制,目前是有寫出方法來,但感覺太冗長,想請教各位大神有沒有更效率的方式,謝謝!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<tr>
<td><label>option</label></td>
<td><select name="option" id="option">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select></td>
</tr>
<br>
<tr>
<td><label>input1</label></td>
<td>
<input type="text" name="no_one" id="no_one">
</td>
</tr>
<br>
<tr>
<td><label>input2</label></td>
<td>
<input type="text" name="no_two" id="no_two">
</td>
</tr>
</div>
</body>
$("#option").change(function () {
if ($(this).val() == 1) {
$("#no_one").attr("disabled", "disabled");
$("#no_two").removeAttr("disabled");
} else if ($(this).val() == 2) {
$("#no_two").attr("disabled", "disabled");
$("#no_one").removeAttr("disabled");
} else {
$("#no_one").removeAttr("disabled");
$("#no_two").removeAttr("disabled");
}
}).trigger("change");
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<tr>
<td><label>option</label></td>
<td><select name="option" id="option">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select></td>
</tr>
<br>
<tr>
<td><label>input1</label></td>
<td>
<input type="text" name="no_one" id="no_1">
</td>
</tr>
<br>
<tr>
<td><label>input2</label></td>
<td>
<input type="text" name="no_two" id="no_2">
</td>
</tr>
</div>
</body>
jQuery
$.fn.disableInput = function () {
$("input[id^='no_']").prop('disabled', true);
var input = $("#no_" + $(this).val()).length > 0 ? "#no_" + $(this).val() : "input[id^='no_']";
$(input).prop('disabled', false);
}
$("#option").change(function () {
$(this).disableInput();
}).trigger("change");
提供參考
如果要變更選項與 disable 元素的規則,修改 hideSetting 的設定就可
$("#option").change(function () {
//設定要被隱藏的 id
let hideSetting = {
"1": ["no_one"],
"2": ["no_two"],
"3": []
};
let arr = hideSetting[$(this).val()];
$('input[id^="no_"]').each(function () {
$(this).prop("disabled", arr.indexOf($(this).attr("id")) >= 0);
});
}).trigger("change");