2016-11-07 48 views
-3

檢查此頁:如何啓用禁用的文本框時,特別複選框通過JavaScript

<input type="checkbox" checked id="chk1" onclick="myFunction(this)" /> 
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" /> 
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" /> 
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" /> 

<input type="text" id="txt1" disabled="disabled" /> 
<input type="text" id="txt2" disabled="disabled" /> 
<input type="text" id="txt3" disabled="disabled" /> 
<input type="text" id="txt4" disabled="disabled" /> 

<script> 
    function myFunction(el) { 
     var txt = document.getElementById(el.id.replace('chk', 'txt')); 

     if (el.checked) { 
      document.getElementById(txt).removeAttribute("disabled"); 
     } 
     else 
      document.getElementById(txt).setAttribute("disabled", "disabled"); 
    } 
</script> 

我已經試過這個劇本,但它給誤差

"Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object"

回答

0
function myFunction(el) { 
    var txt = document.getElementById(el.id.replace('chk', 'txt')); 

    if (el.checked) { 
     txt.removeAttribute("disabled"); 
    } 
    else 
     txt.setAttribute("disabled", "disabled"); 
} 

See working demo。如果它仍然不適用於喲,只需將您的腳本移到HTML標記上方即可。

+0

使用此腳本未啓用文本框 –

+0

@snehanagaruru更新了答案。 – Imad

0

你有一個錯誤的腳本部分:

var txt = document.getElementById(el.id.replace('chk', 'txt')); 

這給你回textbox沒有ID的整個元素。如果你改變這個它應該工作:

<script> 
    function myFunction(el) { 
     var txt = el.id.replace('chk', 'txt'); 

     if (el.checked) { 
      document.getElementById(txt).removeAttribute("disabled"); 
     } 
     else 
      document.getElementById(txt).setAttribute("disabled", "disabled"); 
    } 
</script> 

您可以在此JSFiddle測試(請注意,我也刪除您checkboxes在撥弄例如checked屬性)

0

用戶與var txt = el.id.replace('chk', 'txt');

代替 var txt = document.getElementById(el.id.replace('chk', 'txt'));

無需使用document.getElementById,因爲你已經使用電子申報字元素在myFunction(this)

而且隨着true | false

function myFunction(el) { 
 
     var txt = el.id.replace('chk', 'txt'); 
 

 

 
     if (el.checked) { 
 
      document.getElementById(txt).disabled = false; 
 
     } 
 
     else 
 
      document.getElementById(txt).disabled = true; 
 
    }
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" /> 
 
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" /> 
 
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" /> 
 
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" /> 
 

 
<input type="text" id="txt1" disabled> 
 
<input type="text" id="txt2" disabled> 
 
<input type="text" id="txt3" disabled> 
 
<input type="text" id="txt4" disabled>

0

適用disabled有了這個說法,你會惱火文本框

var txt = document.getElementById(el.id.replace('chk', 'txt')) 

但你不應該使用這個

document.getElementById(txt).removeAttribute("disabled"); 

但這

txt.removeAttribute("disabled"); 

例如看到小提琴

https://jsfiddle.net/zxrxcs5k/

相關問題