J888
J888

Reputation: 1964

How to show and hide multiple forms on the same page?

I have few radio buttons that each is associated to a separate div. Once user choose one, its associated div will be shown, the problem is that once I choose an option and its div is shown if I choose the next option, the style of previous div wont be hidden.

I think to solve this issue I should have a separate function to make all the divs hidden before showing the new one, but I am wondering if there is any other alternative to this.

 $(document).ready(function() {
                $("input[name=options]:radio").change(function() {
                    alert($(this).val());
                 $('#' + $(this).val()).show();
                })
            });


   radio btns go here .... 
  <div id="1" style="display:none">
    ......
  </div>

  <div id="2" style="display:none">
    ....
  </div>

Upvotes: 0

Views: 942

Answers (2)

Nis
Nis

Reputation: 1477

As I have commented in Arun's answer ..

$(document).ready(function() {
            $("input[name=options]:radio").change(function() {
                alert($(this).val());

             $("div.divToToggle").hide().filter('#' + $(this).val()).show();
            })
        });

radio btns go here .... 
<div id="1" class="divToToggle" style="display:none">
 ......
</div>

<div id="2" class="divToToggle" style="display:none">
 ....
</div>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

just hide the forms before showing the target form like

$(document).ready(function () {
    $("input[name=options]:radio").change(function () {
        $('form').hide();//you may have to improve this form selector if there are unrelated forms in the page
        $('#' + $(this).val()).show();
    })
});

Since div's are used without any way to group them add a new class to all the targetted divs like

<div id="1" class="form-ct" style="display:none">......</div>
<div id="2" class="form-ct" style="display:none">......</div>

then

$(document).ready(function () {
    $("input[name=options]:radio").change(function () {
        $('.form-ct').hide();//you may have to improve this form selector if there are unrelated forms in the page
        $('#' + $(this).val()).show();
    })
});

Upvotes: 1

Related Questions