使用jQuery向输入字段添加最大值 [英] Add a max value to input field with jQuery

查看:450
本文介绍了使用jQuery向输入字段添加最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的减号/加号jsfiddle从输入字段中添加或删除数字.但是,我试图找出设置最大值的最佳方法,这意味着,如果用户尝试键入大于10的数字或使用加号功能,则他们不能超过10. ?

I am using a simple minus/plus jsfiddle to add or remove a number from an input field. However, I am trying to figure out the best way to set a max value meaning that if a user attempted to either type a number greater than 10 or used the plus feature that they cannot go past 10. What is the best way to achieve that?

jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    // If is not undefined
    if (!isNaN(currentVal)) {
        // Increment
        $('input[name='+fieldName+']').val(currentVal + 1);
    } else {
        // Otherwise put a 0 there
        $('input[name='+fieldName+']').val(0);
    }
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[name='+fieldName+']').val());
    // If it isn't undefined or its greater than 0
    if (!isNaN(currentVal) && currentVal > 0) {
        // Decrement one
        $('input[name='+fieldName+']').val(currentVal - 1);
    } else {
        // Otherwise put a 0 there
        $('input[name='+fieldName+']').val(0);
    }
});

});

jsfiddle

推荐答案

如果您只对JS/jQuery解决方案感兴趣,只需更改第11行:

If you're just interested in a JS/jQuery solution, simply change line 11:

 if (!isNaN(currentVal) && currentVal < 10) {
                       ^~~~~~~~~~~~~~~~~~~^---------[Add this to line 11

http://jsfiddle.net/zer00ne/snwxaLx7/

要将值保留为10而不是重置为0,请更改第16行:

To keep the value to 10 rather than to reset to 0, change line 16:

      $('input[name=' + fieldName + ']').val(10);
                                             ^^-----[Change 0 into 10

http://jsfiddle.net/zer00ne/v1pje44v/

这篇关于使用jQuery向输入字段添加最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆