[英]enabled and disabled text input on checkbox checked and unchecked
我有復選框和文本輸入
我需要的是在選中復選框時啟用文本輸入,並在取消選中復選框時禁用文本輸入
我正在使用以下代碼,但它在未選中時反向啟用/選中時禁用,因此如何調整它以滿足我的需要。
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
任何幫助〜謝謝
您只需要添加一個!
在this.checked
前面。
這是一個顯示更改的示例:
document.getElementById('yourBox').onchange = function() { document.getElementById('yourText').disabled = !this.checked; };
<input type="text" id="yourText" disabled /> <input type="checkbox" id="yourBox" />
一個 jQuery 解決方案可能是這樣的:
<script>
$('#yourBox').change(function() {
$('yourText').attr('disabled',!this.checked)
});
</script>
它與 Minko 的答案相同,但我覺得它更優雅。
嘗試一下。 如果您使用標簽,則向其添加 onmousedown
<form > <input type="text" id="yourText" disabled /> <input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/> </form>
更好的解決方案可能是:
var checkbox = document.querySelector("#yourBox"); var input = document.querySelector("#yourText"); var toogleInput = function(e){ input.disabled = !e.target.checked; }; toogleInput({target: checkbox}); checkbox.addEventListener("change", toogleInput);
<input type="checkbox" id="yourBox"> <input type="text" id="yourText">
function createInput( chck ) { if( jQuery(chck).is(':checked') ) { jQuery('<input>', { type:"text", "name":"meta_enter[]", "class":"meta_enter" }).appendTo('p.checkable_options'); } else { jQuery("input.meta_enter").attr('disabled','disabled'); } } createInput( chck );
<input type="radio" name="checkable" class="checkable" value="3" /> <input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.