使用jQuery根据动态无线电输入属性值更改总输入值 [英] Change total input value according to dynamic radio input attribute values with jQuery

查看:60
本文介绍了使用jQuery根据动态无线电输入属性值更改总输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助添加,删除,更改总输入值中无线电输入元素的数据动态属性值。

Need help with adding, removing, changing the values of data-dynamic attribute of radio input elements from the total input value.

动态生成的无线电输入

<input type="radio" id="valetId" name="valetId" value="0" data-dynamic="0" />
<input type="radio" id="valetId" name="valetId" value="1" data-dynamic="20" />
<input type="radio" id="valetId" name="valetId" value="2" data-dynamic="40" />

,总投入为:

<input type="text" id="Total" name="Total" class="form-control" value="" />

到目前为止,我有jQuery脚本,它添加了无线电输入数据 - 动态总值

So far I have the jQuery script, that adds the radio input data-dynamic values to total

  $("input[type=radio]").click(function(event) {
    //alert('Button pressed with value: '+dynamicValue);
        $("input[type=radio]:checked").each(function() {
            total = Number($('#Total').val()) + $(this).data('dynamic');
        });
    $('#Total').val(total);
  });

我需要有关如何删除已检查的无线电输入的帮助 data-dynamic 来自总计的属性,如果选中则添加第二个无线电输入 data-dynamic 属性,或者如果无线电输入<$ c,则将总输入值重置为原始价格选中$ c> data-dynamic 属性为0。

I need help with how to remove the checked radio input data-dynamic attribute from the total, add the 2nd radio input data-dynamic attribute if checked or reset the total input value to original price if radio input data-dynamic attribute with 0 is checked.

谢谢。

推荐答案

您应该使用更改事件,该事件仅在您检查无线电时调用。 (未经检查时不会触发,因此您不需要减去)

然后您不必遍历所有无线电,而只需获取已检查的无线电的值。

You should use change event which is only called when you check a radio. (it will not fire when unchecked, so that you don't need to substract)
Then you don't have to loop through all the radios, but just grab the value of the radio which has been checked.

var total, myVal;
$("input[type=radio]").change(function(event) {
    // check if 'myVal' variable is defined, if not, set it to the input field value (or 0 if it's empty):
    if(myVal === undefined){
       myVal = ( parseInt($('#Total').val()) || 0);
    }
    total = myVal + parseInt($(this).attr('data-dynamic'));
    $('#Total').val(total);
});

DEMO

编辑

如果输入字段的初始可以手动更新(通过输入),您可以使用它。它只会在使用复选框更新时获取输入字段值:

If the input field initial value can be updated manualy (by typing in), you could use this. It will only grab the input field value when it was updated not using check-boxes:

var inputVal, prevData, total = $('#Total');
$("input[type=radio]").change(function() {
    var dynamicData = parseInt($(this).attr('data-dynamic')),
        totalVal = parseInt(total.val());
    if(inputVal === undefined || totalVal !== prevData + inputVal){
        inputVal = (totalVal || 0);
    }
    total.val(inputVal + (prevData = dynamicData));
});

DEMO

确保所有收音机都唯一的 id 属性。

Make sure that all of your radios have unique id attribute.

这篇关于使用jQuery根据动态无线电输入属性值更改总输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆