简体   繁体   English

如何在Jquery或js中设置最小值和最大值的限制

[英]how to set the limit of minimum and maximum value in Jquery or js

I have this script for increment decrements value of a text box, it's working fine.我有这个脚本来增加文本框的递减值,它工作正常。 Only thing I need to achieve is, I have to set a minimum and maximum value for it to decrements and increments receptively.我唯一需要实现的是,我必须为它设置一个最小值和最大值,以便接受地递减和递增。

I don't need any alert n message to show the user, I just need it should not change the value after reaching to the limit.我不需要任何警报 n 消息来向用户显示,我只需要它在达到限制后不应更改该值。

  <script>
    $(document).ready(function(){
  $("#up").on('click',function(){
    $("#incdec input").val(parseInt($("#incdec input").val())+1);
   });

   $("#down").on('click',function(){
    $("#incdec input").val(parseInt($("#incdec input").val())-1);
   });

 });
 </script>

Demo演示

You can use following.您可以使用以下内容。 Just set max and min value in data-max and data-min attribute in up and down buttons;只需设置max和在最小值data-maxdata-min在属性updown按钮;

<input type="button" id="up" value="Up" data-max="5"/>
<input type="button" id="down" value="Down" data-min="0"/>

And in js;在 js 中;

$(document).ready(function() {
    $("#up").on('click',function(){
          if ($("#incdec").val() < $(this).data("max")) {
            $("#incdec").val(parseInt($("#incdec").val())+1);
          }
    });

    $("#down").on('click',function(){
          if ($("#incdec").val() > $(this).data("min")) {
            $("#incdec").val(parseInt($("#incdec").val())-1);
          }
    });
});

Edit: For image buttons : Demo 2编辑:对于图像按钮:演示 2

Edit2: How about if you creating that buttons dynamically more than once? Edit2:如果你不止一次动态地创建按钮怎么样?

Let say you have generating buttons dynamically and generate an output like below;假设您动态生成按钮并生成如下输出;

<div>
    <input type="text" class="incdec" value="0"/>
    <input type="button" class="up" value="Up" data-max="5"/>
    <input type="button" class="down" value="Down" data-min="0"/>
</div>

<div>
    <input type="text" class="incdec" value="0"/>
    <input type="button" class="up" value="Up" data-max="5"/>
    <input type="button" class="down" value="Down" data-min="0"/>
</div>

....

And you can use following js:您可以使用以下js:

$(document).ready(function() {
    $(".up").on('click',function(){
          var $incdec = $(this).parent().find(".incdec");
          if ($incdec.val() < $(this).data("max")) {
            $incdec.val(parseInt($incdec.val())+1);
          }
    });

    $(".down").on('click',function(){
          var $incdec = $(this).parent().find(".incdec");
          if ($incdec.val() > $(this).data("min")) {
            $incdec.val(parseInt($incdec.val())-1);
          }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM