Search code examples
copyradio-buttonchecked

radio buttons check and uncheck remove and replace input values


I have two radio buttons with label name A & B and two groups of text boxes with class names groupA and groupB.My requirement is When user checks radiobutton A then all the values from Group B text boxes will clear and when user checks Radiobutton B then GroupB text boxes again fill with their original values and Group A textboxes values will clear vice versa. For this i am able to clear textboxes values based on class.But i how to fill all the previous values when user checks one of the radiobutton?Below is my code.

jQuery(function(){
    jQuery("#id1").click(function() {     
            jQuery(".groupB").each(function()
            {
               jQuery('input.groupB[type="text"]').val('');
            });
        }
    });

jQuery("#id2").click(function() {     
            jQuery(".groupA").each(function()
            {
               jQuery('input.groupA[type="text"]').val('');
            });
        }
    });

});

Any help would be greatly appreciated.


Solution

  • You didn't show your HTML, so I'm not sure I have the fields right. But here is what I came up with:

    <body>
      <form>
        <input id="id1" type="radio" name="test" value="A" />Group A
        <input type="hidden" name="hidden_a1" />
        <input type="hidden" name="hidden_a2" />
        <input class="groupA" type="text" name="text_a1" disabled="disabled" />
        <input class="groupA" type="text" name="text_a2" disabled="disabled" />
        <br />
        <input id="id2" type="radio" name="test" value="B" />Group B
        <input type="hidden" name="hidden_b1" />
        <input type="hidden" name="hidden_b2" />
        <input class="groupB" type="text" name="text_b1" disabled="disabled" />
        <input class="groupB" type="text" name="text_b2" disabled="disabled" />
      </form>
    </body>
    

    and here is the JavaScript code:

    $(document).ready(function() {
      $('#id1').on('click', {
        show: 'A',
        hide: 'B'
      }, choose_group);
      $('#id2').on('click', {
        show: 'B',
        hide: 'A'
      }, choose_group);
    });
    
    function choose_group(event) {
      $('.group' + event.data.show).each(function(index) {
        $(this).prop('value', $('[name="' + $(this).prop('name').replace('text', 'hidden') + '"]').prop('value'));
        $(this).prop('disabled', false);
      });
      $('.group' + event.data.hide).each(function(index) {
        $('[name="' + $(this).prop('name').replace('text', 'hidden') + '"]').prop('value',
          $(this).prop('value'));
        $(this).prop('value', '');
        $(this).prop('disabled', true);
      });
    }