gpt4 book ai didi

jquery - 正/负最大值输入

转载 作者:行者123 更新时间:2023-11-28 05:21:57 25 4
gpt4 key购买 nike

我有一个加号/减号按钮,希望用户不能选择超过 20 个但不知道如何让它工作。我尝试使用 min="1"max="5 属性,但它们不起作用。这是我的代码和一个 fiddle 链接。https://jsfiddle.net/6n9298gp/

<form id='myform' method='POST' action='#' class="numbo">
<input type='button' value='-' class='qtyminus' field='quantity' style="font-weight: bold;" />
<input type='text' name='quantity' value='1' class='qty' style="margin-bottom: 0px !important" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
<input type='button' value='+' class='qtyplus' field='quantity' style="font-weight: bold;" />
</form>

<script type="text/javascript">
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);
$('.qtyminus').val("-").removeAttr('style')
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(1);

}
});
// 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 > 1) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(1);
$('.qtyminus').val("-").css('color','#aaa');
$('.qtyminus').val("-").css('cursor','not-allowed');
}
});
});
</script>

最佳答案

<input type="number" min="1" max="20" step="1">

然后你可以使用脚本来传递验证消息(只是因为浏览器内置的数字字段消息目前很差)。

这消除了对库的依赖,遵循 HTML 规范,并免费内置了辅助功能。

如果您仍然需要 +/- 按钮来满足设计限制,请确保您使用减号字符 (&#8722;),然后在正确的字段类型之上逐步增强您的脚本。这样,如果您的 jQuery 未下载(例如网络中断)或页面上存在脚本错误,任何情况都不会导致整个系统崩溃。

如果 +/- 按钮不能满足设计要求,请考虑完全放弃它们。

您还可以针对可能遇到 type="number" 问题的浏览器逐步增强此功能(虽然你可以看到 support is pretty good pattern support 更好)没有脚本通过将模式匹配放入元素中,尽管这是一个非常边缘的情况:

<input type="number" min="1" max="20" step="1" pattern="[0-9]*">

您可以阅读 more on type="number" in the HTML5 specthe language reference .

关于jquery - 正/负最大值输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37665060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com