Search code examples
javascriptjqueryradio-button

Add to value based on radio button value


This is hard to describe so I'll try my best.

I have a script working fine, based on the radio button selected, it prints the value to a text box that is disabled for editing. I have to take this one step further...I need that value to then be involved in an addition function, adding the value of the radio button.

This is what I tried and it failed. No errors but doesn't add what I want it to. If I remove the if statements, it works but only prints the initial value of the radio button. I need to add to that value based on what is selected.

edit: adding html as requested.

<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>

Solution

  • I rewrite your script code if I did not misunderstand your intent;

    $('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);
    
        });