[英]check box checked on page load and show output
Below is my working code but the only problem is, I want the check box to checked by default and show the jquery output on page load but it only show output when i re-check the check box. 下面是我的工作代码,但唯一的问题是,我希望默认情况下选中此复选框,并在页面加载时显示jQuery输出,但仅在我重新选中该复选框时才显示输出。
http://jsfiddle.net/pratyush141/2mq5sr1h/ http://jsfiddle.net/pratyush141/2mq5sr1h/
$(function() {
$defaultValue = $('.total').val();
$("input[type=checkbox]").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="invoice">
<input type="checkbox" checked='checked' value="1" />
<span class="inv-total">$100</span>
</div>
<input type="text" class="total" value="$90" />
It's simple, just remove the checked=checked from the checkbox, then use jquery to call the click on checkbox 很简单,只需从复选框中删除checked = checked,然后使用jquery调用单击复选框即可
<div class="invoice">
<input type="checkbox" value="1" />
<span class="inv-total">$100</span>
</div>
$(function () {
$defaultValue = $('.total').val();
$("input[type=checkbox]").change(function (event) {
var total = 0;
$("input:checked").each(function () {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
} else {
$('.total').val('$' + total);
}
});
//Call the click on checkbox
$("input[type=checkbox]").click();
})
Working fiddle: http://jsfiddle.net/2mq5sr1h/5/ 工作提琴: http : //jsfiddle.net/2mq5sr1h/5/
You set value of input on click event. 设置点击事件的输入值。 You need to set it in $(document).ready()
. 您需要在$(document).ready()
。 Try to change your script to this: 尝试将脚本更改为此:
$(document).ready(function (){
setValue();
$("input[type=checkbox]").click(function(event) {
setValue();
});
});
function setValue()
{
$defaultValue = $('.total').val();
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('.total').val($defaultValue);
}
else {
$('.total').val('$' + total);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.