David Gonzalez David Gonzalez - 1 year ago 74
Javascript Question

JavaScript More Efficient code to hide all element expect cloest

I have about 20 Forms. When A button the closes form should unhide.

And all the other forms should remain hidden. '

This is the way i was doing it

$(document).ready(function() {
console.log( "ready!" );

$(".toggle-new-form1").click(function() {
// $("input[name='union_name']").focus();
$(".toggle-new-form2").click(function() {
// $("input[name='union_name']").focus();


This is sample of html

<div class="form-group" style="">
<label >Email:</label>
<button type="button" id="new" style="margin-top:7px;" class="toggle-new-form pull-right btn btn-primary">Edit</button>
<p> example@gmail.com </p>
<form id="name-form" class="new-form1 hidden" method="POST" action="">
<input id="email">
<button type="submit"> Submit </button>

But i am having trouble hiding previously activated forms.

Is there anyway to make this more efficient and hide previously activated forms.

I have tryed this as well

<script type="text/javascript">

$(document).ready(function() {
console.log( "ready!" );

$(".toggle-new-form").click(function() {
$(this).closest( ".new-form" ).removeClass( "hidden" )


I dont know how its working

Js fiddle https://jsfiddle.net/0p2brLww/2/

Answer Source

You can try something like this a single click event for all the buttons+forms

$(document).ready(function() {
      $('[class^="toggle-new-form"]').click(function() {
       var el = $(this).parent().next();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download