如何在jquery中启用和禁用文本框

时间:2013-12-18 12:29:05

标签: javascript jquery html

我已经编写了一个html和脚本的示例代码,如下所示: 当我执行此代码时,我将获得该警报你好,但当我通过按Tab键更改cca然后它没有显示警报时的其他警报。如何使用该文本框并启用和禁用其他文本字段。

HTML:

<div id="cca" class="leaf">
     <label class="control input text" title="">
        <span class="wrap">cca</span>
        <input class="" type="text" value="[Null]">
        <span class="warning"></span>
     </label>
</div>

JS:

jQuery(document).ready(function () {        
    alert("hello");        
    jQuery("#cca label.control input").on('change', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

2 个答案:

答案 0 :(得分:2)

我不确定你要做什么,但我可以帮助让警报正常工作。你基本上没有使用jQuery&#34; on&#34;功能正常。

$('#thisNeedsToBeContainer').on('focusout', '#elemToBindEventTo', function (event)....

以下其中一项将满足您的需求:

当文本框保留时会触发

$(document).ready(function () {      

    alert("hello");        
    $("#cca").on('focusout', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

这将触发change

$(document).ready(function () {       
    alert("hello");        
    $("#cca").on('change', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

这将在keyup上点击

$(document).ready(function () {  
    alert("hello");        
    $("#cca").on('onkeyup', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

请参阅JsFiddle

上的演示

您还应该关闭输入:

<input class="" type="text" value="[Null]"/>

答案 1 :(得分:1)

您正在侦听change事件,该事件在输入失去焦点之前不会触发。鉴于您提供的代码确实会在焦点离开输入后触发警报(通过制表符或单击),我猜您在键入后但在更改焦点之前期待响应。要实现这一点,请改为倾听input事件。

相关问题