我正在创建一个表单,在这种情况下,用户可以在此字段中从输入字段的值中进行加减,以显示多个子代。
自然,我可以从屏幕上显示的数字中进行加减,但是当我在控制台中签入时,实际值保持为0。对我来说很重要的一点是能够检查该值,以便我可以设置最小值和最大值。
如何确保单击按钮时值会发生变化?
JS:
childVal = $('#pageSearch-children').val();
minValueChild = $('#pageSearch-children').attr('min');
maxValueChild = $('#pageSearch-children').attr('max');
if (childVal < maxValueChild) {
$('.add').click(function () {
$('#pageSearch-children').val( function(i, oldval) {
return ++oldval;
});
$('#pageSearch-children').val() + 1;
});
}
if (childVal > minValueChild) {
$('.sub').click(function () {
$('#pageSearch-children').val( function(i, oldval) {
return --oldval;
});
$('#pageSearch-children').val() - 1;
});
}
HTML:
<h3 class="white black">
<input class="backgroundNoneInput" type="number" value="0" id="pageSearch-children" name="children" min="0" max="{{ $property--property_sleeps or '99' }}">
</h3>
<button type="button" class="sub backgourndNoneButt">
<span class="white fa fa-minus fa-2x faPlusMin" aria-hidden="true">
</span>
</button>
<button type="button" class="add backgourndNoneButt">
<span class="white fa fa-plus fa-2x faPlusMin" aria-hidden="true">
</span>
</button>
答案 0 :(得分:3)
我希望您将代码更改为以下内容,以使其更好地工作:
childVal = $('#pageSearch-children').val();
minValueChild = $('#pageSearch-children').attr('min');
maxValueChild = $('#pageSearch-children').attr('max');
$('.add').click(function() {
if (childVal < maxValueChild) {
$('#pageSearch-children').val(function(i, oldval) {
return ++oldval;
});
childVal = $('#pageSearch-children').val();
}
});
$('.sub').click(function() {
if (childVal > minValueChild) {
$('#pageSearch-children').val(function(i, oldval) {
return --oldval;
});
childVal = $('#pageSearch-children').val();
}
});
问题之一是您的$('.sub').click
永远不会运行,因为它永远不会在原始代码中传递if (childVal > minValueChild) {
。
演示
childVal = $('#pageSearch-children').val();
minValueChild = $('#pageSearch-children').attr('min');
maxValueChild = $('#pageSearch-children').attr('max');
$('.add').click(function() {
if (childVal < maxValueChild) {
$('#pageSearch-children').val(function(i, oldval) {
return ++oldval;
});
childVal = $('#pageSearch-children').val();
}
});
$('.sub').click(function() {
if (childVal > minValueChild) {
$('#pageSearch-children').val(function(i, oldval) {
return --oldval;
});
childVal = $('#pageSearch-children').val();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="white black">
<input class="backgroundNoneInput" type="number" value="0" id="pageSearch-children" name="children" min="0" max="99" readonly> Children
</h3>
<button type="button" class="sub backgourndNoneButt">
<span class="white fa fa-minus fa-2x faPlusMin" aria-hidden="true"> sub
</span>
</button>
<button type="button" class="add backgourndNoneButt">
<span class="white fa fa-plus fa-2x faPlusMin" aria-hidden="true"> add
</span>
</button>