【发布时间】:2016-06-07 09:44:36
【问题描述】:
我正在使用以下代码(不是我的),我正在尝试让增量按钮仅针对与它们相关的表单。但是,当您有多个如下所示的表单时,增量框会增加页面上的两个(所有)输入框。
如何仅定位我正在使用的表单?
我确定这是一个简单的解决方法,但我无法弄清楚!请帮忙!
提前一百万谢谢!
艾略特。
<form id='myform' method='POST' action='#'>
<input type='button' value='-' class='qtyminus' field='quantity' />
<input type='text' name='quantity' value='0' class='qty' />
<input type='button' value='+' class='qtyplus' field='quantity' />
</form>
<form id='myform' method='POST' action='#'>
<input type='button' value='-' class='qtyminus' field='quantity' />
<input type='text' name='quantity' value='0' class='qty' />
<input type='button' value='+' class='qtyplus' field='quantity' />
</form>
<script>
$(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);
}
});
});
</script>
【问题讨论】:
-
这和你的问题无关,但是你不应该给多个元素赋予相同的id('myform')。