Clearing A Form And Closing The Div After Successful Post
Solution 1:
To clear the form you can call the reset()
method of the underlying Element. I'm not sure what you mean by 'close the div', but you can call hide()
to make it disappear. Try this:
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
Also note that it would be much better practice to return JSON from the AJAX call. You can then have a boolean flag to show the state of the request.
Update
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Given that is the code of your button there is another issue - you're not preventing the form from being submit, hence the AJAX request is cancelled. To do this, hook to the submit
event of the form instead of the click of the button. From there you can call e.preventDefault()
to stop form submission. Try this:
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
});
});
});
</script>
Note I used a generic 'form'
selector above. You can change that to a class or id selector on the form as required.
Solution 2:
For clearing form fields
$("input[type=text], textarea").val("");
cheers
Solution 3:
you can also use Triggers as well
$('#form_id').trigger("reset");
Post a Comment for "Clearing A Form And Closing The Div After Successful Post"