场景:如果我单击按钮无值,则值= 0,弱值= 1,中等值= 2,否则值= 3。总计将显示在sub_total中。但是,我有一些问题如何为此计算创建JavaScript。这是我的HTML代码。
<td>{!! Form::radio('que_1',0,null) !!}</td>
<td>{!! Form::radio('que_1',1,null) !!}</td>
<td>{!! Form::radio('que_1',2,null) !!}</td>
<td>{!! Form::radio('que_1',3,null) !!}</td>
<td>{!! Form::radio('que_2',0,null) !!}</td>
<td>{!! Form::radio('que_2',1,null) !!}</td>
<td>{!! Form::radio('que_2',2,null) !!}</td>
<td>{!! Form::radio('que_2',3,null) !!}</td>
这是我的javascript。
<script>
$(document).ready(function () {
var $radios = $(':radio[name^="que_"]').change(function () {
var totalPrice = $radios.filter(function () {
return this.checked && this.value === '1'
}).length;
$('#sub_total').val(totalPrice);
});
$radios.first().change()
});
如何创建具有4个值的js?
答案 0 :(得分:0)
假设渲染的标记看起来像:
<table>
<tr>
<td><input type="radio" name="que_1" value="0"></td>
<td><input type="radio" name="que_1" value="1"></td>
<td><input type="radio" name="que_1" value="2"></td>
<td><input type="radio" name="que_1" value="3"></td>
</tr>
<tr>
<td><input type="radio" name="que_2" value="0"></td>
<td><input type="radio" name="que_2" value="1"></td>
<td><input type="radio" name="que_2" value="2"></td>
<td><input type="radio" name="que_2" value="3"></td>
</tr>
</table>
(我不习惯Laravel)
然后,为了总结已检查无线电的值,jQuery将是:
$(document).ready(function () {
// Define the total variable globally.
var totalPrice = 0;
var $radios = $("[type='radio']"); // Can be $("[name^='que_']") here...
$radios.change(function () {
// Reset total on each change.
totalPrice = 0;
// Sum up the checked.
$("[type='radio']:checked").each(function(){ // And here, can be $("[name^='que_']:checked")
totalPrice += parseInt( $(this).val() );
});
// Show the result.
$('#sub_total').val(totalPrice);
});
// On load first calculation...
$radios.first().change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="radio" name="que_1" value="0"></td>
<td><input type="radio" name="que_1" value="1"></td>
<td><input type="radio" name="que_1" value="2"></td>
<td><input type="radio" name="que_1" value="3"></td>
</tr>
<tr>
<td><input type="radio" name="que_2" value="0"></td>
<td><input type="radio" name="que_2" value="1"></td>
<td><input type="radio" name="que_2" value="2"></td>
<td><input type="radio" name="que_2" value="3"></td>
</tr>
</table>
<br>
<input id="sub_total">