如果输入值已更改但未更改回默认值,则禁止显示按钮

时间:2017-01-10 18:52:44

标签: jquery

我已经设置了简化的代码段,以帮助您理解我的问题。

代码的条件会在任何输入值更改时添加类名。 我的目标是为了防止在输入值发生变化时显示更新按钮,但在我们的情况下将值更改为默认值“1”。

// Bind an action on input change event
$( "#quantity" ).on('input',function(e){

  // Following happens if the value is not equal to 1
  if($("#quantity").val() != "1"){

    // Show the update button
    $( "#update" ).addClass( "show" );

  }

});
.hide{display:none}
.show{display:inline-block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="quantity" type="text" name="quantity" value="1">

<button id="update" type="submit" class="hide">Update</button>

2 个答案:

答案 0 :(得分:2)

你可以添加这个

$(document).ready(function() {
  $("#quantity").on('keyup', function(e) {
    if ($("#quantity").val() === "1") {
      $("#update").removeClass("show").addClass("hide");
    } else {
      $("#update").removeClass("hide").addClass("show");
    }
  });
})

这里是js小提琴

https://jsfiddle.net/bb085grp/4/

答案 1 :(得分:1)

只需在函数中添加grid子句即可将类更改回else。还在函数的第一部分添加了hide

removeClass
// Bind an action on input change event
$( "#quantity" ).on('input',function(e){

  // Following happens if the value is not equal to 1
  if($("#quantity").val() != "1"){

    // Show the update button
    $( "#update" ).removeClass( "hide" );
    $( "#update" ).addClass( "show" );

  } else {

    // Show the update button
    $( "#update" ).removeClass( "show" );
    $( "#update" ).addClass( "hide" );
  }

});
.hide{display:none}
.show{display:inline-block}

相关问题