Javascript load fresh form - javascript

I have a simple form which is opened within a modal when an anchor is clicked.
<a id="callbackLink" class="various" href="#inline">Request</a>
<div id="inline" style="display:none">
<form id="callForm" onsubmit="callEvent(event);">
<h3>Call Back</h3>
<label for="Number">What number shall we call you on?</label>
<input type="tel" id="callback-tel" placeholder=""><br>
<input type="submit" value="Submit" />
</form>
</div>
When the form is submitted, a third party library processes the form. If the form is successful, the form is removed and a success message is displayed in the modal.
Now if you close the modal and then click the button to display the form again, it will still show the success message. So I need a way of displaying a clean form every time the button is pressed.
What would be the best way to achieve this?
UPDATE
The event listener is
function StartClickToCall(event) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
var SuccessfulRequest = function() {
document.getElementById('ClickToCallForm').style.display = 'none';
document.getElementById('ClickToCallErrorMessage').style.display = 'none';
document.getElementById('ClickToCallSuccessMessage').style.display = 'block';
};
var FailedRequest = function(Request, Response) {
document.getElementById('ClickToCallSuccessMessage').style.display = 'none';
document.getElementById('ClickToCallErrorMessage').style.display = 'block';
document.getElementById('ClickToCallErrorMessage').innerHTML = Response.ResponseMessage;
};
_novero.push(['NoveroCallback', 'NewCallback', {
Destination : jQuery("#callback-tel").intlTelInput("getNumber"),
CallbackDate : document.getElementById('CallbackDate').value
}, SuccessfulRequest, FailedRequest]);
}

$('#myModal').modal('toggle');
$('#myModal').modal('view');U can try with modal window cleaning.I think modal window seems to be problem

you didnt post the correct part of the code
if the form is replaced by a success message, then you probably have a function that is making an ajax call and in the success callback you are removing the from HTML and put in the success message HTML
if so .. if you wan to restore the form on modal close . then you need to attach a function to close click that will remove the success message HTML and re-insert the Form HTML
EDIT:
$(".selector").fancybox({
onClosed: function() {
document.getElementById('ClickToCallForm').style.display = ‘block’;
document.getElementById('ClickToCallErrorMessage').style.display = ‘block’;
document.getElementById('ClickToCallSuccessMessage').style.display = ‘none’;
};
});
something like this . (you deleted the fancy declaration) . the close method might have a different name
but what is happening:
on fancy modal close . switch back the styles of the form . that are overwritten in the success function

Related

Bootstrap Modal not adding modal-open class to body when triggered via Javascript

I have a Modal on my page whose content changes depending on which of two buttons is clicked (an <input />'s value changes). To better add functionality, I have set up an additional block of that is supposed to manual open the Modal if there's an error to show.
To make sure the form is "sticky", I manually trigger the click event on the corresponding button and what not. However, when I manually trigger the click event, Bootstrap is not adding .modal-open to the body. Due to how my site is built, without .modal-open on the body, the Modal is completely hidden behind other content.
So obviously I'm doing something wrong, but I have no idea. Here's a copy of my code:
<?php
$modalerror = false;
$id = 0;
if (/*Basic check for errors*/) {
$modalerror = true;
$id = /*Get the correct id*/;
}
?>
<script type="text/javascript">
jQuery( document ).ready(function($) {
$('#modal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
if (button.attr('data-name') && button.attr('data-name') != '') {
$('#name').val(button.attr('data-name'));
} else {
$('#name').val('');
}
});
});
<?php if ($modalerror) { ?>
jQuery ( window ).load(function() {
jQuery('button[data-id=<?php echo $id; ?>]').trigger('click');
});
<?php } ?>
</script>
Upon further inspection/progress, I noticed that it I manually trigger the Modal in the exact same fashion somewhere else on the page/later on, there aren't any problems with adding the .modal-open class to the body. Code sample:
<script type="text/javascript">
function manualOpen(id) {
jQuery('button[data-id="'+id+'"]').trigger('click');
}
</script>
<button type="button" onclick="manualOpen(/*Correct id*/);">Open</button>
Even more testing, I added a second modal to the page with completely different contents that opens automatically under very specific circumstances, it does not need to load custom content based off of a buttons data-* attributes. This second Modal suffers the exact same problem if it doesn't also have some form of timeout (as mentioned in my comment to this question).
Using bootstrap 4, the best way IMO without using timeouts is adding a function in the closing event of the modal.
When a modal is closing and there is a command for open another modal before it completes the closing action, the new modal is open but the class .modal-open is not added to the body.
The next function open a modal checking if there is an opened modal. The new modal is opened directly or in the closing event callback depending of the case. This function requires that every modal has an id.
function openModal(modalid) {
//Looks for current modal open
if ($('.modal.fade.show').length > 0) {
//Gets the id of the current opened modal
var currentOpenModalId = $('.modal.fade.show').attr('id');
//Attaches a function to the closing event
$('#' + currentOpenModalId).on('hidden.bs.modal', function () {
//Opens the new model when the closing completes
$('#' + modalid).modal('show');
//Unbinds the callback
$('#' + currentOpenModalId).off('hidden.bs.modal');
});
//Hides the current modal
$('#' + currentOpenModalId).modal('hide');
} else {
//If is not an opened modal, the new modal is opened directly
$('#' + modalid).modal('show');
}
}
I am using Bootstrap 4.1.1 and jQuery 3.3.1, and faced the same problem. 50ms didn't solved the problem. So, i had to bump it upto 500ms, and it worked!
//hide first
$('#modal1').modal('hide');
//add delay when showing next modal
setTimeout(function () {
$('#modal2').modal('show');
}, 500);
I'm using bootstap 4.3.1 and modified 'bootstrap.min.js' file
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
g(document.body).removeClass(ce); // ce = 'modal-open'
t._resetAdjustments(),
t._resetScrollbar(),
...
to
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
if (document.getElementsByClassName('modal fade show').length == 0) {
g(document.body).removeClass(ce);
}
t._resetAdjustments(),
t._resetScrollbar(),
...
It works very well

jquery post in new opened window

I have a page where I enter a text in an input, it is a simple form. I have a button and when I hit the button, is it possible to open another page and post the data to this new window via jquery. I am not talking about ajax here because I want to open a new window and go to that new page holding the post form.
So I have page 1 with form and input 1. I enter test in input 1 and then if I hit submit, it will open a new php page where there is a
$_POST['temp']
And it will be filled in so that the code executes automatically. In fact, this is to avoid entering everything in the url and going to that url.
It seems I was not clear enough. I know how to do it with a form and a submit button. But I would like to submit the form via jquery so when I hit a button or something else that will be intercepted by my javascript, it will look up the input and then redirect to the other page and post with data I want.
If I understood correctly you want to access parent window form input value from a child window (popup) opened by the parent.
If that is the case I suggest you look at window.opener property
http://www.w3schools.com/jsref/prop_win_opener.asp
If you have a parent window like this:
HTML:
<form id="testForm">
<input type="text" id="testVariable" value="" />
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('#testForm').on('submit', function(e){
e.preventDefault();
window.open('http://www.yourdomain.com/chilwindow.php', 'ChildWindow', 'menubar=0,resizable=1,location=0,scrollbars=0,status=0,toolbar=0,width=580,height=520');
});
});
Then in your child window/popup (http://www.yourdomain.com/chilwindow.php) you should be able to access you parent window like this:
$(document).ready(function () {
var testVariableNew = window.opener.$("#testVariable").val();
console.log('Got value from parent window: ' + testVariableNew);
});
Or:
$(document).ready(function () {
var testVariableNew = $('#testVariable', window.opener.document).val();
console.log('Got value from parent window: ' + testVariableNew);
});
If you want to do a POST request do the following:
$( "#testForm" ).submit(function(e) {
e.preventDefault();
var myVariable = $(this).find("#testVariable").val();
var myUrl = $(this).attr("action");
var posting = $.post( myUrl , { temp: myVariable } );
posting.done(function(result) {
console.log(result);
});
});
The jquery.form.js plugin does exactly what you want.
http://malsup.com/jquery/form/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function(response) {
alert("The script said: "+response);
});
});
</script>
</head>

how to change form on change button click?

I have two json files "a.json" and "b.json". I need to show a different form when the user clicks each of the different buttons. My issue is that when I click on the first button it show the first form, but when I click on the second button it doesn't show the second form. I need to show one form at a time, i.e. when I click the second button it removes the first form and shows the second form.
$scope.getFromAFile= function () {
// body...
var inputs=[];
$http.get('a.json').success (function(data){
var a=changeData(data);
$scope.formFields=[]
console.log('pp');
console.log(data.studentName);
console.log($scope);
$scope.formFields = a['input'];
}).error(function(err){
alert(err);
});
}
$scope.getFromBFile= function () {
// body...
$http.get('b.json').success (function(data){
var a=changeData(data);
console.log('pp');
$scope.formFields=[]
console.log(data.studentName);
console.log($scope);
$scope.formFields = a['input'];
}).error(function(err){
alert(err);
});
}
here is plunker
http://plnkr.co/edit/tuMl02QcvZkCCIJPTW0r?p=preview
Dont mix JQuery with AngularJs
you can use ng-click and ng-show for achieving such Task
<button ng-click="hideFormOne()">Hide Form One</button><!-- Hides Form One & Shows Form Two -->
<button ng-click="hideFormTwo()">Hide Form Two</button><!-- Hides Form Two & Shows Form One-->
<form ng-show="showFormTwo">
:
:
<form ng-show="showFormOne">
:
:
script
$scope.hideFormOne = function()
{
$scope.showFormOne = false; // Hides Form One
$scope.showFormTwo = true; // Shows Form Two
}
$scope.hideFormTwo = function()
{
$scope.showFormTwo = false; // Hides Form Two
$scope.showFormOne = true; // Shows Form One
}
If i understand u can use hide() function:
on document load u need hide both forms:
$('#form1').hide();
$('#form2').hide();
And on button click:
$('#button1').click(function(){
$('#form1').show();
$('#form2').hide();
});
$('#button2').click(function(){
$('#form1').hide();
$('#form2').show();
});
You can have two forms, eg formA and formB.
And then if user click on formA, hide formB or click on formB then hide formA.
Example if clicked formA:
$('formA').hide();
$('formB').show();
And example if clicked formB:
$('formA').show();
$('formB').hide();
Here is Plunker Demo

On submit, load a html popup file into a div

I am trying to redirect to a contact form on submit to a HTML file which I have made using.
header('Location: /dev/thanks.html');
However, this loads it to a different page and not to the page that I'm already on.
I already have the jQuery to make a popup for the contact form and information page, which is:
$('a.contact , a.contact_footer, a.contact_text').click(function() {
$("html, body").animate({ scrollTop: 0 }, 600);
$("#popup").load("/dev/contact.php");
// Getting the variable's value from a link
var show = $('#popup').css('display', 'block'),
popup = $(this).attr('href');
//Fade in the Popup and add close button
$(popup).fadeIn(300);
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
On submitting the contact form, I want to load a new file (thanks.html) to replace the popup (contact form) with a thank-you message. Similar to what I'm doing with the jQuery already, but I want it to only implement on submit:
<div class="submit">
<input type="submit" value="Submit"/>
</div>
What do I need to do to modify my jQuery so it implements on submit instead of on click?
Add the submit event to the contact form:
If you use jQuery 1.7+, use on:
$(document).on("submit", "form#submit_message", function() {
$('#popup').load('/dev/thanks.html');
return false;
});
If not, use live (or upgrade your jQuery version):
//live is old deprecated
$('form#submit_message').live('submit', function() {
$('#popup').load('/dev/thanks.html');
return false;
});
I'm assuming that the form will append directly in the "#popup", without that you will have to change the "var popup..." line.
$("#popup").on("submit", "form", function(event){
var popup = $(this).parent();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "my_url.php",
data: data
}).done(function(html){
popup.html(html);
});
return false;
});

Is there a way to check if a postback is in progress?

In the case that a button is clicked multiple times on a page - Is there a way to figure out using javascript/jquery that a postback is already in progress and cancels the new attempt to submit the page?
Thanks
You can avoid users from double clicking by disabling whatever form elements can cause a form submit.
Checkout http://greatwebguy.com/programming/dom/prevent-double-submit-with-jquery/ for an example.
You can disable the button on first click, so that you could not click it when the post is in progress, and re enable it when the post-back has finished.
<script type="text/javascript" language="JavaScript">
var submitted = false;
function SubmitTheForm() {
if(submitted == true) { return; }
document.myform.submit();
document.myform.mybutton.value = 'Thank You!';
document.myform.mybutton.disabled = true;
submitted = true;
}
</script>
<form method="post" action="#">
<input type="submit" onclick=return SubmitTheForm()>
</form>
you could always just disable the button in the onclick handler.
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var self = this;
$(self).attr('disabled', 'disabled');
$.post('url',$(self).closest('form').serialize(), function() {
$(self).removeAttr('disabled'); // re-enable after request complete.
});
});
You could have your click event set a variable in your click handler to true and only allow the handler to proceed when the value is false. Of course you will have to set it to false again when your callback finishes.
if (!processInProgress) {
processInProgress = 1
// start the process
}

Categories

Resources