Search code examples
jqueryarraysradio-buttonlabel

radio + label hot to get correct values (array)


I'm trying to get correct values form labels (radio). When I click label, I'm getting value but when I click another one (label), I'm getting value from the first label and I need to click it once again to get two values to my array.

I'm gonna hide radio buttons as I want to use only labels. How I can avoid this behavior ?

Have a look:

var radioChecked = $('#radioinstant :radio').is(':checked');

$('#radioinstant :radio').click(function() {
        radioChecked = !radioChecked;
    $(this).attr('checked', radioChecked);
});

var additionalProducts = new Array;

    $(".chk").click(function() {
        additionalProducts=[];
        $('.chk:checked').each(function() {
            additionalProducts.push($(this).val());
        });
        console.log(additionalProducts);
        alert(additionalProducts);
    });

http://jsfiddle.net/qfagc/


Solution

  • You're clearing the array on every click.

    var additionalProducts = new Array;   <--- this creates the array
    
        $(".chk").click(function() {
            additionalProducts=[];     <--- this clears the array on EVERY CLICK
            $('.chk:checked').each(function() {
                additionalProducts.push($(this).val());
            });
            console.log(additionalProducts);
            alert(additionalProducts);
        });