复选框和单击事件处理

时间:2015-04-06 19:36:12

标签: javascript c# jquery

我尝试将文本框设置为' readonly',添加一个类,然后在我选中复选框时将文本放入文本框。此外,我还试图删除' readonly'来自文本框的属性,添加一个类,并删除文本框中的文本。

我有

$('#CheckBoxSectionCode').click(function () {
    if ($(this).is(':checked')) {
        $('#TextBoxSectionCode').attr('readonly', 'readonly');
        $('#TextBoxSectionCode').addClass('disabled');
        $('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
        }
    else {
        $('#TextBoxSectionCode').attr('readonly', false);
        $('#TextBoxSectionCode').addClass('abled');
        $('#TextBoxSectionCode').text('');
    }
});

此代码对我不起作用。

谢谢,

菲利普


感谢大家的回答。

根据您的评论和回答,我已经更改了我的代码,但它仍无效。

$('#CheckBoxSectionCode').click(function () {
    if ($(this).is(':checked')) {
        $('#TextBoxSectionCode').prop('readonly', true);
        $('#TextBoxSectionCode').addClass('disabled');
        $('#TextBoxSectionCode').text('disabled');

    }
    else {
        $('#TextBoxSectionCode').prop('readonly', false);
        $('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
        $('#TextBoxSectionCode').text('');
    }
});

我使用Chrome浏览器运行此代码,并使用chrome中的开发人员工具,并在上面的代码中设置一个断点,以查看jquery中发生了什么。但是,当我单击复选框以选中/取消选中时,没有任何反应。

4 个答案:

答案 0 :(得分:1)

document.getElementById('TextBoxSectionName').val这是错误的。你真的应该缓存你的jQuery对象,这样它就不会一遍又一遍地导航DOM。然后你混合使用原生JS和.val不是DOM属性或方法,也不是jQuery属性,对于DOM对象应该是.value,对于jQuery对象应该是.val()

@Archy Wilhes的强制性解释:

  

"只是为了澄清;当@SterlingArcher说缓存jQuery对象时   她/他的意思是做一些像var obj = $('#TextBoxSectionCode')   然后使用这样的变量调用函数:   obj.attr(...); obj.addClass(...)。每次你做$(某事)你   正在jQuery中调用一个查找DOM的函数。"

答案 1 :(得分:0)

因为每次添加类时,元素最终都会同时拥有这两个类。在添加其他类之前,请考虑删除其他类。例如,

$(selector).removeClass('disabled').addClass('enabled')

答案 2 :(得分:0)

尝试使用更改事件而不是单击:

    $('#CheckBoxSectionCode').change(function () {
        if ($(this).is(':checked')) {
        $('#TextBoxSectionCode').attr('readonly', 'readonly');
        $('#TextBoxSectionCode').addClass('disabled');
        $('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
    }
    else {
        $('#TextBoxSectionCode').attr('readonly', false);
        $('#TextBoxSectionCode').addClass('abled');
        $('#TextBoxSectionCode').text('');
    }

});

答案 3 :(得分:0)

你可以采取以下方式。

//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
    //Use prop as opposed to attr
    textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
    if ($(this).is(':checked')) {
        textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
    }
});
相关问题