如果值为false或true,则禁用和激活按键功能

时间:2018-11-14 15:11:46

标签: javascript keypress

我在输入上按下按键,如下所示:

$('.input-name').keypress(function(e){
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if(keycode == '13'){
        e.preventDefault();
        myFunction();
    }
});

如果我按下Enter键,则会调用myFunction()。

现在,我想检查另一个值是false还是true ...,然后停用并激活按键。我怎么做?下面检查var is_name是true还是false:

var is_name;

$('.input-name').on('input', function () {      
    is_name = $('#abcName').val();
    if ( is_name == false ) {
        $('button.filter').attr('disabled','disabled');

        // Deactivate keypress

    } else {
        $('button.filter').removeAttr('disabled');

        // Activate keypress        

    }
});

2 个答案:

答案 0 :(得分:0)

您需要某种状态。您的情况由is_name设置。如果is_name虚假,则按Enter键将不起作用,并且将不会执行myFunction

var is_name = "";
var
    $nameInput = $('.input-name'),
    $filterButton = $('button.filter');

function myFunction() {
    console.log('Meow');
}

$nameInput.on('keyup', function (e) {      
    is_name = $(this).val();
    // toggles the disabled property
    $filterButton.prop( "disabled", !is_name );
    console.log(is_name + ' is' + (!!is_name ? " " : " not ") + ' valid');
    var keycode = (e.keyCode ? e.keyCode : e.which);
    // if block won’t be executed if is_name is falsy
    if(keycode == '13' && !!is_name){
        e.preventDefault();
        myFunction();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="input-name" /><button class="filter" disabled>Do something</button>

答案 1 :(得分:0)

您可以使用OnOff

进行切换

$(function(){

$("#change_event").change(function(){

  var is_name = $(this).val();

  if (is_name == "true")
  {
    console.log(is_name + " Keypress event Added");
    $('.input-name').on('keypress', function(){ console.log("Keypress event"); })
  }
  else
  {
    console.log(is_name + " Keypress event Removed");
    $('.input-name').off('keypress')
  }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="change_event">
<option value="">Choose</option>
<option value="true">Add Event</option>
<option value="false">Remove Event</option>
</select>

<input class="input-name" />