On Key press cancel change event of text box and on button click trigger change event of text box jquery

时间:2017-12-18 06:18:39

标签: javascript jquery

I want to cancel change event of a text box on keypress then I want to trigger it on button click. This is example of my HTML

$('#btn1').on('click', function() {
    var target = '#test';
    $(target).on("change");
    $(target).focus();
    $(target).val('HELLO').trigger('change');
});

$("#test").change(function(event) {
    alert($(this).val())
});
$('#test').on('keypress', function(event) {
    if (event.keyCode === 13) {
       event.stopImmediatePropagation();
       $(this).off("change");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="submit" id="btn1" value="BUTTON1" />

but it is not firing change event.

Please suggest.Thanks in advance.

JSFiddle

3 个答案:

答案 0 :(得分:1)

$('#btn1').on('click', function () {
                var target='#test';
        $(target).on("change",changeText($(target)));
        $(target).focus();
        $(target).val('HELLO').trigger('change');
});

function changeText($this) {
     alert($this.val())
}
$('#test').on('keypress', function (event) {
      event.stopImmediatePropagation();
      $(this).off("change");
});

event was not in function param and trying to use propogation https://jsfiddle.net/0624eq86/20/

答案 1 :(得分:1)

i think you forget add "event" in javascript code

replace :

$('#test').on('keypress', function() {
   event.stopImmediatePropagation();
   $(this).off("change");
});

with:

$('#test').on('keypress', function(event) {
   event.stopImmediatePropagation();
   $(this).off("change");
});

答案 2 :(得分:1)

function test(val){
    alert(val);
}
$('#btn1').on('click', function() {
    var target = '#test';
    $(target).focus();
    $(target).val('HELLO').trigger('change');
    $(target).on("change", test($(target).val()));
});

$('#test').on('keypress', function(event) {
    event.stopImmediatePropagation();
    $(this).off("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="submit" id="btn1" value="BUTTON1" />

Please check the answer, I hope this will work for you. I have created a function test, which is called when I ON the change event on click function.