Javascript Question

How to toggle form visibility dynamically?

I have page where user can dynamically create new forms. For every new form button is created. Form is hidden by default. I need to toggle form visibility on that button click. Right now i am using javascript code below and its working

$(document).ready(function(){
$("#button1").click(function(){
$("#1").css({"display":"block"});
$("#2").css({"display":"none"});
$("#3").css({"display":"none"});

});
$("#button2").click(function(){
$("#2").css({"display":"block"});
$("#1").css({"display":"none"});
$("#3").css({"display":"none"});
});
...


Now when user create form i manually modify javascript but problem is that i have too many forms right now and ill have even more.
I need solution to bind button for form and toggle its visibility. Any advice is appreciate.
EDIT
Code i am actually using:

while ($row = $result9->fetch_assoc())
{
echo "<input class='btn btn-default' type='button' id='".$row['o_ime']."' name='button' value='".$row['o_ime']."'>";
}
echo "<form class='form-inline' role='form' name='$i' id='$i' style='display:none' action='naruci.php' method='POST' onsubmit='return validateForm()'>";
form elements
echo "</form>";

Answer

First of all, you cannot have the same ID in your DOM.

So instead of IDs use classes. And use jquery's class selector.

So to capture the event, just use the class selector.

And also use hide and show jquery APIs to show/hide elements.

 $(".new-btn").click(function(){
       $("form").hide(); // close all forms
       $("this").closest("form").show(); // show parent form
    });

And the next thing I notice, for dynamic elements it cannot be captured by normal click event. Use jquery on API.

$(".new-btn").on('click', function(){
    $("form").hide(); // close all forms
    $("this").closest("form").show(); // show parent form
});

Update: It should look like this:

while ($row = $result9->fetch_assoc()) 
{
    echo "<input class='btn btn-default' type='button' id='".$row['o_ime']."'  name='button' value='".$row['o_ime']."'>";

    // We changed the form ID in this section   
    echo "<form class='form-inline' role='form' name='$i' id='form_".$row['o_ime']."' style='display:none' action='naruci.php' method='POST' onsubmit='return validateForm()'>";
    form elements
    echo "</form>";
}

In my query I will create an event to capture my button clicks:

$('.btn').on('click', function(){ // Listen all click events of buttons with class `btn`
    var id = $(this).attr('id');  // Get ID of focus button
    var formName = 'form' + id;   // Append form string in the id to match form's ID

    $('form').hide();             // Hide all forms
    $('#' + formName).show();     // Show exact form
});