Search code examples
jqueryformsradio-button

Calculating the price with radio value in jQuery


Apparently this should be doing but doesn't work :

http://jsfiddle.net/9baeJ/

HTML :

<form id="myForm">
    <label>
        20
        <input id="fb3" type="radio" name="fb1" value="20" />
    </label>

    <label>
        35
        <input id="fb4" type="radio" name="fb1" value="35" />
    </label>

    <label>
         10
         <input id="fb1" type="radio" name="fb" value="10" />
     </label>

    <label>
        15
        <input id="fb2" type="radio" name="fb" value="15" />
    </label>
    <br/>
    Total: <span id="totalScore">0</span>€
</form>

And the js :

var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function (i, e){sum+=$(e).val();});
$("#totalScore").val(sum);

I tried everything I saw here in stackoverflow but I don't get what's wrong with the code. Actually this solution is one of the examples that somebody already posted.


Solution

  • Trythis

    function calcscore(){
        var score = 0;
        $("input[type='radio']:checked").each(function(){
            score+=parseInt($(this).val());
        });
        $("#totalScore").text(score)
    }
    $().ready(function(){
        $("input[type='radio']").change(function(){
            calcscore()
        });
    });
    

    DEMO