David Gonzalez David Gonzalez - 2 months ago 6
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() {
$(".new-form1").toggleClass("hidden");
// $("input[name='union_name']").focus();
});
$(".toggle-new-form2").click(function() {
$(".new-form2").toggleClass("hidden");
// $("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>
</div>
<form id="name-form" class="new-form1 hidden" method="POST" action="">
<input id="email">
<button type="submit"> Submit </button>
</form>


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() {
$(".new-form").addClass("hidden");
$(this).closest( ".new-form" ).removeClass( "hidden" )
});


});
</script>


I dont know how its working

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

Answer

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();
           $('[class^="new-form"]').not(el).addClass('hidden');
           el.toggleClass("hidden");
     //$(this).parent().next().find("input[name='union_name']").focus();
  });

});
Comments