[英]How to increment the counter value when the input field is filled?
这是我的laravel
视图代码。 在这里,我正在尝试增加计数器值(即value =“ 0/5”)。 我在模态中有输入字段,单击模型内部的保存按钮时,该值应根据填充的输入字段而增加。ie(1 / 5..2 / 5 ..)
我试图增加这些计数器的值。但它显示的是NaN
var val; $("input").click(function() { val = $('#counter').val(); val++; $('#counter').prop('value', val) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-title pull-left"> <i class="fa fa-check-circle" style="font-size:20px;color:lightgreen"> </i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none"> </div>
<script type="text/javascript">
$("input").click(function() {
let val = parseInt($('#counter').val().split('/')[0]);
$('#counter').prop('value', `${++val}/5`);
});
</script>
实际上,您的代码运行良好。 由于您将视图包含在一个模态内,该模态仅在click事件中显示或显示,因此您应该使用jQuery“ on ”方法来增强您的click handler函数定义。 在这种情况下,您应该使代码正常工作
var val; $(document).on('click','#counter',function() { val = $('#counter').val(); val++; $('#counter').prop('value',val ) });
<div class="panel-title pull-left"> <i class="fa fa-check-circle" style="font-size:20px;color:lightgreen"> </i> Price,stock and Shipping Information<input type="submit" id="counter" **value="0/5"** style="background-color: transparent; border:none"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
您可以使用正则表达式来解析/
字符之前的数据
var val;
$("input").click(function() {
val = $('#counter').val();
qty = val.match(/[^/]*/i)[0];
qty++;
$('#counter').prop('value', qty)
});
如果您想像这样增加1/5..2/5
split
并仅增加上限值。
var val; $("input").click(function() { val = $('#counter').val().split("/"); //check eqal value with base if(val[0] == val[1]) { return false; } val[0]++; $('#counter').prop('value', val[0]+"/"+val[1]); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-title pull-left"> <i class="fa fa-check-circle" style="font-size:20px;color:lightgreen"> </i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none"> </div>
您也可以尝试一下。
$("#counter").on("click",function(){ var counterBtn = document.getElementById("counter"); var count = counterBtn.value; //alert(count.split("/")[0]); count = count.split("/"); counterBtn.value = ((parseInt(count[0])+1)%(parseInt(count[1])+1))+"/"+count[1]; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-title pull-left"> <i class="fa fa-check-circle" style="font-size:20px;color:lightgreen"> </i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none"> </div>
这是您的解决方案:
$("input").click(function() {
var val = $('#counter').val();
$('#counter').prop('value', `${++val % 6}/5`);
});
和工作的小提琴:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.