Use javascript to close all opened forms before op

2019-12-16 20:09发布

I'm making an html page with images, where the user clicks their image, to log in to their invoice page. This is what I have so far:

<script type="text/javascript">
   function showHideForm(formid) 
    {
       var _form = document.getElementById(formid);
      _form.style.display = (_form.style.display != "block") ? "block" : "none";
       return false;
    }
</script>

<p>
  <a href="#" onclick="return showHideForm('hiddenForm1');">
    <img src="" width="150" height=    "150" />
  </a>
</p>
<form  id="hiddenForm1" style="display: none;" method="post" action="user1_login.php">
  <input type="text" name="user" placeholder="Name" required /><br />
  <input type="text" name="pass" placeholder="Password" required/><br />
  <input type="submit" name="Submit" value="Submit" />
</form>

<p>
  <a href="#" onclick="return showHideForm('hiddenForm2');">
    <img src=""  width="150" height="150" />
  </a>
</p>
<form  id="hiddenForm2" style="display: none;" method="post" action="user2_login.php">
  <input type="text" name="user" placeholder="Name" required /><br />
  <input type="text" name="pass" placeholder="Password" required/><br />
  <input type="submit" name="Submit" value="Submit" />
</form>

It works nicely except that if you click on other images, you get several instances open at the same time.

Is it possible to tack a bit of code to the beginning of the javascript to close any open instances before it runs the code to open a new form?

1条回答
成全新的幸福
2楼-- · 2019-12-16 20:41

The logic is simple, have a class for openedform. On click event remove that class from the existing opened forms and add the class to the currently clicked form. Here is how to do it with jquery.

 function showHideForm(formid) 
 {
    // var _form=$("#"+formid);  (in jquery)

    var _form =document.getElementById(formid);
    //select all existing opened forms and remove the class
    $('.openedForm').removeClass('openedForm');
    //add the openedForm class to the currently clicked 
    $(_form).addClass('openedForm');
    return false;
 }

Add the following code into your css file.

  .openedForm
     {
        display:block !important;
     }

If you need to alter the css of elements using javascript try to use classes. This way you make your javascript code cleaner and readable and your styling logic stays separated from the main logic. Avoid using inline styles as much as possible.

Working demo:
https://jsbin.com/nigivu/edit?html,css,js,output

查看更多
登录 后发表回答