使用Javascript启用和禁用输入字段

时间:2014-12-28 15:03:13

标签: javascript css html-form

我已经编写了一些简单的代码,可以在按钮点击时启用和禁用输入字段,但它没有响应。 请帮帮我...... !!!

<html>
<head>
    <script type="text/javascript">
        function toggleEnable(el1, el2) {
            document.getElementByID(el1).disabled = true;
            document.getElementByID(el2).disabled = true;
        }
    </script>
</head>
<body>
    <form>
        <table>
            <tr>
                <td><input id="input1" class="myText" type="text" placeholder="Row 1" /></td>
                <td><input id="input2" class="myText" type="text" placeholder="Row 1" /></td>
                <td><button onclick="toggleEnable('input1','input2')"> Enable/Disable </button></td>
            </tr>
            <tr>
                <td><input id="input3" class="myText" type="text" placeholder="Row 3" /></td>
                <td><input id="input4" class="myText" type="text" placeholder="Row 4" /></td>
                <td><button onclick="toggleEnable('input3','input4')"> Enable/Disable </button></td>
            </tr>
        </table>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

您的按钮正在提交所在的表单,为了不提交您必须使用type="button"按钮的表单,您也拼错了getElementByID错误的getElementById 1}}

<form>
    <table>
        <tr>
            <td><input id="input1" class="myText" type="text" placeholder="Row 1" /></td>
            <td><input id="input2" class="myText" type="text" placeholder="Row 1" /></td>
            <td><button type="button" onclick="toggleEnable('input1','input2')"> Enable/Disable </button></td>
        </tr>
        <tr>
            <td><input id="input3" class="myText" type="text" placeholder="Row 3" /></td>
            <td><input id="input4" class="myText" type="text" placeholder="Row 4" /></td>
            <td><button type="button" onclick="toggleEnable('input3','input4')"> Enable/Disable </button></td>
        </tr>
    </table>
</form>
    function toggleEnable(el1, el2) {
        document.getElementById(el1).disabled = true;
        document.getElementById(el2).disabled = true;
    }

http://jsfiddle.net/mowglisanu/aam7jg9t/

答案 1 :(得分:0)

function toggleEnable(id) {
   var textbox = document.getElementById(id);
   
   if (textbox.disabled) {
      // If disabled, do this 
       document.getElementById(id).disabled = false;
    } else {
       // Enter code here
        document.getElementById(id).disabled = true;
     }
}
<form>
    <table>
        <tr>
            <td><input id="input1" class="myText" type="text" placeholder="Row 1" /></td>
            <td><button type="button" onclick="toggleEnable('input1')"> Enable/Disable </button></td>
        </tr>
        <tr>
            <td><input id="input2" class="myText" type="text" placeholder="Row 2" /></td>
            <td><button type="button" onclick="toggleEnable('input2')"> Enable/Disable </button></td>
        </tr>
    </table>
</form>