Meules
Meules

Reputation: 1389

How to Check/uncheck dynamic radio buttons in javascript?

This question is asked probably a million times but I can't get this one to work.

I have 3 radio buttons which are created normally. I want to place a 4th radio button between the first and third radio button. When clicking this radio button the third and fourth radio button should appear and unchecking this radio should make them disappear.

To clarify I created a fiddle

So what I tried is below. I created a new div with the radio. Injected it after the first radio. This works ok! When I check the newly created radio the 3rd and 4th appear. So works ok! The problem is when I click the first radio, the second keeps checked so the 3rd and 4th radio is are still visible. I thought that it would work with .prop or I'm obviously doing something wrong.

Anybody?

$(document).ready(function () {
    var newContainer = $('<div class="gui-spacer"></div><div class="gui-block-option"><div class="gui-field"><div class="gui-radio"><div class="tm-radio"><input type="radio" value="" name="shipment_method_wholesale" id="gui-form-shipping-wholesale" class=""></div><label for="gui-form-shipping-wholesale">Ik wil graag bij mijn groothandel bestellen(Afhalen)</label></div><div class="gui-field-content"><p>text over bestellen bij groothandel</p></div></div></div>');

    $('#gui-form .gui-block-option:not(:first)').hide();
    $('#gui-form-shipping-wholesale').prop('checked', false);
    $('#gui-form .gui-block-option:first').after(newContainer);


    $('input[name="shipment_method_wholesale"]').bind('change', function () {

        var showOrHide = ($(this).val() == 1) ? false : true;
        $('#gui-form .gui-block-option:not(:first) ').toggle(showOrHide);
        $(this).prop('checked', true);
    });
});

Upvotes: 0

Views: 965

Answers (2)

James Brierley
James Brierley

Reputation: 4670

Radio buttons are grouped by their name property. If you want to ensure that only one can be selected at a time then make sure that they have the same name.

All I did to get your jsfiddle to work was change the name of the radio button you were dynamically adding to shipment_method.

var newContainer = $('<div class="gui-spacer"></div><div class="gui-block-option"><div class="gui-field"><div class="gui-radio"><div class="tm-radio"><input type="radio" value="" name="shipment_method" id="gui-form-shipping-wholesale" class=""></div><label for="gui-form-shipping-wholesale">Ik wil graag bij mijn groothandel bestellen(Afhalen)</label></div><div class="gui-field-content"><p>text over bestellen bij groothandel</p></div></div></div>');

Edit: I had to make some other changes to get it hiding and displaying the other buttons correctly

Upvotes: 2

Sehab
Sehab

Reputation: 259

To be part of the same group you need to make the "name" attribute the same for all buttons part of that group.

Upvotes: 0

Related Questions