根据单选按钮值添加值

时间:2015-03-22 15:05:16

标签: javascript jquery add radio

这很难描述,所以我会尽我所能。

我的脚本工作正常,根据所选的单选按钮,它会将值打印到禁用编辑的文本框。我必须更进一步......我需要该值然后参与添加功能,添加单选按钮的值。

这是我尝试过的,它失败了。没有错误,但没有添加我想要的东西。如果我删除if语句,它可以工作,但只打印单选按钮的初始值。我需要根据所选内容添加该值。

编辑:根据要求添加html。

<center>
Choice1 : <input type="radio" name="region" id="choice1" value="10.25">
Choice2 : <input type="radio" name="region" id="choice2" value="11.25">
Choice3 : <input type="radio" name="region" id="choice3" value="8.25">
</center>

//Enter how many in this box
How many?  <input type="text" id="addtl" size="3" maxlength="2"></input> @ 

//this is the choice, based on radio button, add something to it
<input type="text" id="add_cost" size="2" maxlength="6"></input>

<script>
//print in the box 

$('input[name="region"]').change(function(){
$('#add_cost').val($('input[name="region"]:checked').val());
if(add_cost == 11.25)  {
  add_cost + 4;
}
else if (add_cost == 10.25){
  add_cost + 1;
}
else if(add_cost == 8.25){
  add_cost + 3;
}

});



</script>

2 个答案:

答案 0 :(得分:1)

如果我没有误解你的意图,我会重写你的脚本代码;

$('input[name="region"]').change(function() {
        var add_cost = parseFloat($('input[name="region"]:checked').val());
        if (add_cost == 11.25) {
            add_cost += 4;
        } else if (add_cost == 10.25) {
            add_cost += 1;
        } else if (add_cost == 8.25) {
            add_cost += 3;
        }
        $('#add_cost').val(add_cost);

    });

答案 1 :(得分:0)

您似乎只是通过&#34; add_cost&#34;来引用add_cost文本框。除非您已通过该名称声明变量,否则必须继续寻址$(&#34; #add_cost&#34;)。val()以引用其值。或者只是声明这样一个变量,包含$(&#34; #add_cost&#34;)。val()。

$('#add_cost').val($('input[name="region"]:checked').val());
var add_cost = parseFloat($("#add_cost").val());
if(add_cost == 11.25)  {
  add_cost + 4;
}