简体   繁体   中英

update div with values of radio buttons on page load

I need to collect the values of the checked radio buttons on page load (they are checked on page load) and add them and not only when the user clicks a radio button.

Here's the javascript:

$(function ()
{
    updateDivResult();
    $('input:radio').live('click',updateDivResult);
    $('#1').click();
})
function updateDivResult(){
    if ($("input:radio:checked"))
    {
        price = parseFloat($(this).val());
        $('#price').html(roundNumber(price,2));
    }
};

roundNumber() is a function defined by me. Now it only updates the #price div when the user clicks a radio button.

Also, there are a few groups of radio buttons - how do I only add the value of one radio button from the group to the total price?

Thank you for assistance.

I think you need to loop through the checked values rather than just getting the val() of that selector because it seems like there could be more than one checked.

function updateDivResult(){
    var price = 0;
    $(":radio:checked").each(function(){
        price += parseFloat($(this).val());
    });
    $('#price').html(roundNumber(price,2));                
};

Can you provide more details? I can see you are using jQuery.

You could use

$(document).ready(function() {...});

to run some methods when the document is read.

Moreover you could put a specific class to your html elements and use the "each" function to traverse them.

eg

$('.your_el').each(function() {...});

In that case the handler will be executed on each object with the class "your_el".

Hope this help, even if the problem is not so clear to me.

Che

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM