pHenomen pHenomen - 4 months ago 43
Javascript Question

Replace form with another form on button click

I have 2 forms. I want when button is clicked to show another form on first form position. So just to replace that form.

Form 1

<div id="right">
<form id="contact" class="visible" action="" method="post">
<fieldset>
<input name="fname" placeholder="Ime" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="lname" placeholder="Prezime" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="tel" placeholder="Telefon" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Email" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Pošalji</button>
</fieldset>
</form>
</div>


Form 2

<div id="form2">
<form id="contact2" action="" method="post">
<fieldset>
<input name="fname" placeholder="Ime" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="lname" placeholder="Prezime" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="tel" placeholder="Telefon" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Email" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Pošalji</button>
</fieldset>
</div>


jQuery

$("#contact-submit").on("click", function() {
$("#contact").removeClass("visible");
$("#form2").addClass("visible");
});


So for some reason this is not working. Please help me to solve this. I tried to set
opacity:0;
of first form but it doesn't work. And please let me know which libary is should use.

Here is my example: http://codepen.io/anon/pen/PzKaPa

Answer

EDIT: So I looked at your pen and fixed it so it works: http://codepen.io/anon/pen/OXjEQd

It looks like you'll need to do a couple of things, one of which you might have already: first, place your jquery in a ready function (and make sure you've linked a jquery version in your head tag)--

$(function(){ 
    // your code
});

Then, in your click handler, add a preventDefault():

$('#contact-submit').on('click',function(e){
    e.preventDefault();
    // rest of code
});

e.preventDefault() keeps your submit button from doing it's default action--submitting the form. This lets you perform other actions with the button. If you don't include this, the very first thing that will happen when your button is clicked is form submission, and you'll not get to any of the other code inside your click event.

This also assumes you have a .visible class defined in your css. If not, you'll need to add that as well, or instead of using addClass and removeClass, you'll need to change the display property on the form directly:

$('#contact').css('display','none');
$('#form2').css('display','block');
Comments