siz*_*tic 1 html jquery button fiddle
我有一个加/减按钮,希望用户不能选择超过 20 个,但不知道如何让它工作。我尝试使用 min="1" max="5 属性,但它们不起作用。这是我的代码和小提琴的链接。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>
Run Code Online (Sandbox Code Playgroud)
<input type="number" min="1" max="20" step="1">
然后,您可以使用脚本来传递验证消息(只是因为浏览器中内置的数字字段消息目前很差)。
\n\n这消除了对库的依赖,遵循 HTML 规范,并且免费内置了可访问性。
\n\n如果您仍然需要 +/\xe2\x88\x92 按钮来满足设计限制,请确保使用减号字符 ( −),然后在正确的字段类型之上使用脚本逐步增强。这样,您的 jQuery 无法下载(例如网络中断)或页面上存在脚本错误的任何情况都不会导致整个事情崩溃。
如果您无法通过 +/\xe2\x88\x92 按钮满足设计要求,请考虑完全删除它们。
\n\n您还可以通过将模式匹配放入元素中,为可能遇到困难的浏览器type="number"(尽管您可以看到支持非常好,而pattern支持甚至更好)逐步增强此功能,而无需脚本,尽管这是一个非常边缘的情况:
<input type="number" min="1" max="20" step="1" pattern="[0-9]*">
您可以在 HTML5 规范或语言参考中阅读更多内容type="number"。
| 归档时间: |
|
| 查看次数: |
14716 次 |
| 最近记录: |