如果选中复选框,则禁用文本框

时间:2013-08-29 21:38:31

标签: javascript jquery html checkbox textbox

我有一个HTML表格,每个行都有一个checbox和一个文本框。这里的想法是每次选中复选框时,文本框都将被禁用。这是代码:

 <table>
    <tr>
    <td>Value1</td>
    <td>Value2</td>
    <td><input type="text" class="textbox" /></td>
    <td><input type="checkbox" class="Blocked" onclick="myFunction(this)"/></td>
    </tr>
    </table>


<script src="/Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        function myFunction(chk) {
             //disable the textbox here
        }
    </script>

你能帮我解决这个问题吗?此外,如果我取消选中了checbox,我希望我的文本框能够启用。谢谢!

5 个答案:

答案 0 :(得分:4)

下面的内容会对你有用吗?

$('.Blocked').change( function() {
    var isChecked = this.checked;

    if(isChecked) {
        $(this).parents("tr:eq(0)").find(".textbox").prop("disabled",true); 
    } else {
        $(this).parents("tr:eq(0)").find(".textbox").prop("disabled",false);
    }

});

JSFiddle:http://jsfiddle.net/markwylde/LCWVS/6/

压缩,看起来有点像:

$('.Blocked').change( function() {
    $(this).parents("tr:eq(0)").find(".textbox").prop("disabled", this.checked); 
});

JSFiddle:http://jsfiddle.net/markwylde/LCWVS/4/

答案 1 :(得分:2)

坚持使用内联事件处理程序:

function myFunction(chk) {
    $(chk).closest('tr').find('.textbox').prop('disabled', chk.checked);
}

jQuery方式:

$('.Blocked').change(function() {
    $(this).closest('tr').find('.textbox').prop('disabled', this.checked);
});

答案 2 :(得分:1)

尝试:

function myFunction(chk) {
    document.getElementsByClassName("textbox")[0].disabled = chk.checked;
}

答案 3 :(得分:1)

<input type="text" name="dateFrom" id="t2" style="width:100px"/>
<input type="text" name="dateTo" id="text" style="width:100px"/> 
<script>
$(document).ready(function () {
$('#check').change(function () {
$("#t2").attr("disabled", "disabled");
$("#text").attr("disabled", "disabled");
});
$('#check').click(function () {
if (!$(this).is(':checked')) {
$("#t2").removeAttr("disabled");
$("#text").removeAttr("disabled");
}
});
});
</script>

答案 4 :(得分:0)

尝试此操作它可以禁用和启用文本框,如果要禁用多个文本框,请将其更改为getElementsByClassName(“textboxes”),然后为所有文本字段指定类名。

function disableElement()
{
    textbox = document.getElementById("text");
    if(textbox.disabled)
    {    
        bunit.disabled=false;
    }
    else
    {
        bunit.disabled=true;
    }
}

然后有一个复选框和一个文本字段,文本域名为text

<input type="checkbox" name="check" onclick="disableElement();">
<input type="text" id="text">
相关问题