newsletter popup form, get confirmation in the same window - javascript

I have a popup form but:
- the validation is also a popup and dosnt appear messages
- after submit I would like to get confirmation message in the same popup
<script type="text/javascript">
$(document).ready(function () {
$('#newsletter').click(function (e) {
e.preventDefault();
$('#modal-content').popUpWindow({
action: "open",
modal: true,
size: "large",
buttons: [{
text: "x",
click: function () {
this.close();
}
}]
});
});
});
</script>
<script language="JavaScript" type="text/javascript">
var mailChk =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
function checkSubscribe()
{
if($("#snume").val()==''){
$("#msg").html("sdfsdfsfsfsdf");
$("#snume").focus();
return false;
}if($("#semail").val()==''){
$("#msg").html("sdfsdfsfs");
$("#semail").focus();
return false;
} if($("#semail").val()!='' && !mailChk.test($("#semail").val())){
$("#msg").html("sfsdfsfsfd");
$("#semail").focus();
return false;
}
}
</script>
and the form
<div id="modal-content" class="pop-up-display-content">
<h4>Abonare la newsletter</h4>
<p>Acum te poti abona la newsletter folosind formularul de mai jos.</p>
<?
if(isset($_POST['newsll']))
{
skjdklasjdlka
}
?>
<form action="<?=basename($_SERVER['PHP_SELF']);?>" method="post" enctype="multipart/form-data" >
<?=$msg?>
<input type="text" name="snume" class="k8-frm-input" id="snume" placeholder="Nume si prenume"/><br/>
<input type="text" name="semail" class="k8-frm-input" id="semail" placeholder="Email"/><br/>
<input type="submit" name="newsll" value="submit" id="normal" class="btn k8-btn" onclick="return checkSubscribe()"/>
</form>
</div>
After submit, I get message in the form, if I click again the popup button, I see the message from last submit. But I would like to stay open popup and display message.
And after I close the popup, I would like not to see the last message.
And also, I need the validation to display somewhere... The validation is working because I cant submit form, but no messages appears.
Thanks

Related

Using Jquery Validator and Sweetalert for Form Submission Confirmation Box

I am trying to do the following.
I have 3 buttons, "Continue", "Delete", "New". All of these are type "submit" buttons.
When the form is posted, the value of these buttons is used to determine what happens on the backend.
I want a Sweetalert popup to confirm if the user wants to delete, then when the OK button is hit, the form should progress and submit to the backend.
The issue I currently have is that there is no way to get the value of the submit button to the server side when I incorporate Sweetalert to show when I hit the submit button.
Scenario A) For example, if I remove the "e.preventDefault" from the callback, the alert popups for a brief second but the form submits, not giving the user to confirm or cancel the deletion. This is not correct behaviour, but the "submit" button value does indeed get posted to the server. So to prevent the quick popup issue, I add "e.preventDefault" to stop the normal behaviour of "submit" button.
Scenario B) However, when I have the code as below (i.e. "e.preventDefault" added to the code), the form does not submit after validation. Instead I have to run "$('#myForm').submit()". But when I do this, the value of the "submit" button does not get posted to the server.
If someone could kindly guide me on how I can use jQuery Validate and Sweetalert, it would be much appreciated.
An example of the set up looks like this:
HTML:
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<form id="myForm" action="/postHere" method="post">
<!-- Options-->
<div class="row-select">
<label for="options">My Options</label>
<select name="options" id="options">
<option disabled="true" selected="selected">Select an Option</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
</div>
<!-- continue details form -->
<div>
<input type="submit" id="continue" name="submitButton" value="Continue this Option">
</div>
<!-- delete details -->
<div>
<input class="delete" type="submit" id="delete" name="submitButton" value="Delete this Option">
</div>
<!-- new -->
<div class="row-spaced">
<input type="submit" id="submitButton" name="submitButton" value="Neither" formnovalidate>
</div>
</form>
Javascript:
function myFunction() {
var continueOption = document.getElementById('continue');
var deleteOption = document.getElementById('delete');
var neither = document.getElementById('new');
$('#myForm').validate({
ignore:'',
rules: {
options: "required"
},
});
// AIM IS TO SHOW A CONFIRMATION BOX IF DELETE IS CLICKED
if(deleteOption) {
deleteOption.addEventListener("click", function(e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
console.log("here");
$('#myForm').submit();
}
});
});
}
}
myFunction();
Backend Illustration:
router.post("/postHERE", (req, res) => {
if (req.body.submitButton == "Continue this Option") {
// Do something CONTINUE
}
else if (req.body.submitButton == "Delete this Option") {
// Do something DELETE
}
else {
// Do something NEW
}
}
JSFiddle:
JSFiddle Example
EDIT:
For the backend I am using Expressjs. I have added this in and fixed a type in the form method to be post.

Confirmation Dialog is not showing

I have never worked in jquery before. This is my first time. I need it for some confirmation dialog. I have write this to test it first before applying in my project. I have written this code. I want dialog box only if specified radio button is selected.
Main Problem: Show Confirmation Dialog if Specified Option in radio button is selected.
Jquery code:
(function($){
$.fn.checkLeave = function() {
return this.each(function(){
if($("input[name='second']").is(':checked')) {
alert("Second Radio Button is CLicked");
$.confirm({
text: "Are you sure to submit the form",
title: "Confirmation required",
confirm: function(button) {
$("form").submit();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-default",
cancelButtonClass: "btn-danger",
dialogClass: "modal-dialog modal-lg"
});
}
});
};
})( jQuery );
and HTML is:
<form action="dialogJquery.html" method="post">
<input type="text" name="username" placeholder="Username">
<input type="radio" id="first">
<input type="radio" name="second" checked="">
<input type="submit" value="Submit" id="submit" name="confirm"
onclick="$(this).checkLeave();"></button>
</form>
The above code shows the alert defined before dialog. but after that dialog is not shown. This is from where i am using Jquery Dialog Plugin. But through debugging when debugger reaches $.confirm and i click on step over then dialog is shown but when i resume script it again disappers.
The basic problem is that the form is being submitted because your code is doing nothing to stop it from being submitted. Accordingly, the dialog is being shown only for the duration of time it takes for the browser to submit the form and go to the specified page (dialogJquery.html).
Once someone who is a better programmer looks at this, they can likely come up with a better solution, but following is what I came up with that seems to work. I have added some IDs to elements and such--you should be able to follow that without further explanation. One thing I found is that if any of the elements has a name or ID of "submit" then the .submit() function will not work on the form.
In general, I handle the submit event for the form and preventDefault so that it doesn't submit. The confirm button sets submitConfirm to true and submits the form.
HTML
<form id="myForm" action="dialogJquery.html" method="post">
<input type="text" name="username" placeholder="Username">
<input type="radio" id="first">
<input type="radio" name="second" checked>
<input type="submit" value="Submit" id="btnSubmit" name="confirm">
</form>
Javascript
(function($) {
var submitConfirm = false;
$("#myForm").submit(function(event) {
if (!submitConfirm) {
event.preventDefault();
if ($("input[name='second']").is(':checked')) {
$.confirm({
text: "Are you sure to submit the form",
title: "Confirmation required",
confirm: function(button) {
submitConfirm = true;
$("#myForm").submit();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-default",
cancelButtonClass: "btn-danger",
dialogClass: "modal-dialog modal-lg"
});
}
}
});
})(jQuery);

Alertify confirms and submits a form automatically without clicking OK

I'm creating a blog with bootstrap and I have a form to submit categories:
<form action="categories.php" id="category-form" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<input type="text" name="category" class="form-control" id="category" placeholder="Category">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" id="btn-submit" class="btn btn-primary" value="Add Category">
</div>
</div>
</form>
When I press the form button "Add Category" the dialog appears but after a few seconds it submits itself immediately and the dialog disappears without clicking the buttons "yes" or "no", searching the web I found some solutions but doesn't work for me. The code I use for Alertify JS is the following:
$("#btn-submit").on("click", function(){
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
alertify.success("Category was saved.")
} else {
alertify.error("Category not saved.");
}
});
return false;
});
I also try event.preventDefault();:
$("#btn-submit").on("click", function(event){
event.preventDefault();
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
$("#category-form").submit();
alertify.success("Category was saved.")
return true;
} else {
alertify.error("Category not saved.");
return false;
}
});
});
But does not work as well. Any help please... Thank you.
try something like this. i think you want the confirmation before submitting the form so added the confirm message part. hope it will help.
$("#category-form").submit(function (e) {
var result = confirm("Are you sure ?");
if(result){
// do something
} else {
alertify.error("Error mesage.");
e.preventDefault(); // this will prevent from submitting the form.
}
});
Could you please try following code:
You need to remove type="submit" from your button. Otherwise it submits the form by default.
HTML:
<form action="categories.php" id="category-form" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<input type="text" name="category" class="form-control" id="category" placeholder="Category">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="button" id="btn-submit" class="btn btn-primary" value="Add Category">
</div>
</div>
</form>
JQuery Code:
//your button click code
$("#btn-submit").on("click", function(event){
event.preventDefault();
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
$("#category-form").submit();
alertify.success("Category was saved.")
return true;
} else {
alertify.error("Category not saved.");
return false;
}
});
});
alertify basically take 4 arguments in confirm function
alertify.confirm(title, message, onconfirm, oncancel);
You don't have to do if(e)this code
$("#formID").on("click", function(){
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
alertify.success("Category was saved.")
} else {
alertify.error("Category not saved.");
}
});
return false;
});
will now become
$("#formID").submit(function(e){
e.preventDefault();
alertify.confirm('Confirm Title', 'Confirm Message', function(){
// call the function that will handle your form submission may be ajax don't write $('#fomr').submit() becasue it will start an endless loop through this function
}, function(){
// when user click cancel
});
});
Ok, This was posted and answered a long time ago. But as I was developing asp net
core in 2020, I came across AlertifyJS. I like the library. A solution for this
issue is:
1) I used <button>
2) I used e.preventdefault()
3) I used ('#category-form').submit()
4) Make sure you add id='category-form' in your form and also and id for button.
5) Use button and not input type=submit.
There could be a difference in how they work.
The difference is that <button> can have content,
whereas <input> cannot (it is a null element).
$('#btn-submit').on('click', function (e) {
e.preventDefault();
alertify.confirm('Save Category', 'Do you want to proceed?', function (e)
{
if (e) {
$("#category-form").submit();
alertify.success('Category Saved Successfully.');
return true;
}
else {
alertify.error("Category was not saved.");
return false;
}
}, function () { alertify.error('Cancel') });
});

Popup alert showing prematurely?

I'm working on a submission form that includes a few required fields, and I have a segment of code that allows a popup menu to appear once you hit the "submit" button, and from there once you hit "ok" on the alert you're redirected to the home page. Here's the code I have for the popup alert.
<div id="popup">
<button onclick="myFunction()">Submit</button>
<script>
function myFunction(){
alert("Thank you! \nYour sumbission has been
accepted and you will receive a conformation email shortly! \n
You will now be taken to the Home page.");}
</script> <input type="reset" value="Reset" />
</div>
And this is the beginning of the code for redirecting you to the homepage.
<div id="all">
<div id="text">
<h1>Your Information</h1>
<form id="contact_form" action="home.html" method="post">
<input type="hidden" name="redirect" value="home.html" />
(Note: I clipped the above segment of code because the following information is only the form input boxes)
And this works like you would imagine, the alert popping up once you hit the submit button. However my question is that I have a few required fields on my form, and if the fields are not filled out and you hit "submit", the popup alert appears, and once you hit "ok" on the alert, because you have yet to fill out these fields it takes you back to the form and a little box saying "this field is required" appears.
This is in the wrong order. I want the alert box for the required fields to show before the popup alert for the confirmation of form submission, so that if you have required fields and you hit submit it will tell you to fill out the required fields before the message appears thanking you for submitting.
This may be a simple fix of placement or adding a little code but I'm having a hard time figuring out how to do it or finding an example that could help me.
If you know what to do I'd really appreciate it, thanks!
Edit: This is the javascript file for the validation code.
window.onload = setForm;
function setForm() {
document.forms[0].onsubmit = function() {
if (this.checkValidity()) alert("No invalid data detected. Will
retain data for further testing.");
return false;
}
}
function Validation()
{
vak k = true;
k = function 1 validates field 1 AND returns true or False based On Validation
k = function 2 validates field 2 AND returns true or False based On Validation
k = function 3 validates field 3 AND returns true or False based On Validation
return k;
//At The End Of This Function You Need To Get "TRUE" To Truly Submit.
}
On Submit :
If(Validation() == true)
{
then Only Submit
}
Write Back If It Dosen't Works...
<html>
<body>
<div id="popup">
<textarea cols="30" rows="2" name="required" id="required"></textarea>
<input type="submit" id="click" value="Submit">
<input type="reset" value="Reset" />
</div>
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
var required = document.getElementById("required").value;
if (required===null || required==="") {
alert("Please make sure all required field are completed");
}
else {
alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
window.location.replace("http://stackoverflow.com", 5000);
}
});
</script>
</body>
</html>
http://jsbin.com/wuxahape/1/

Submit behavior is acting differently when pressing a button compared to pressing enter

I've got this simple login screen where is has a text box for the name, and a submit button. The jquery script running is this:
$(document).ready(function() {
$('#btnLogin').click( function() { validate() });
$('#loginForm').submit( function() { validate() });
});
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID=' + $('#txtLogin').val();
$('#lblError').hide();
document.location.href = 'mainmenu.aspx';
}
else {
$('#txtLogin').text('');
$('#lblError').show();
}
}
It works when I click the button, but when I press enter, it doesn't navigate to the mainmenu.aspx. I'm following it with Chrome and it does execute the redirect just like when you press the button, but it just stays on the same page. I also put a break point in the Page_Load function (C#) of the mainmenu.aspx, but it never reaches it.
EDIT:: Here's the html
<form id="loginForm" runat="server">
<div>
<div class='theme login'>
<p>Login</p>
<input type='text' id='txtLogin' maxlength='17' />
<div><input type='button' id='btnLogin' class='button' value='Log In' /></div>
<div><span id='lblError' visible='false' text='*You must enter a valid username'></span></div>
</div>
</div>
</form>
In your form submit handler, use preventDefault() to stop the default submit behavior:
$('#loginForm').submit( function(e) {
e.preventDefault(); // swallow regular submit behavior
validate(); // your stuff
// real submit? your option
});
Reference: http://api.jquery.com/event.preventDefault/
Try making the submit element in the form just a regular button element. The browser may be intercepting something.
The reason for that is your submit still happens when you hit enter. You need to cancel the default behavior by returning false in the event handler function.
function validate() {
// ...
return false;
}
$('#loginForm').submit(validate);
$('#btnLogin').click(validate);
Edit: refer to the function directly instead of an anonymous function?
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID='+$('#txtLogin').val();//set expire and path?
$('#lblError').hide();
location.href = "mainmenu.aspx"; //"submit"
}
else {
$('#lblError').show();
return false; //prevent submit
}
}
$(function() {
$('#btnLogin').click(validate);
$('#loginForm').submit(validate);
});​
I changed both some of your HTML and jQuery code. Now it will check and submit on both Enter and when the button is clicked.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("form").attr("action","javascript:void();"); // No action on form submission
$("input").keypress(function(e) { // Capture keys pressed
if(e.keyCode==13) { // Enter key?
validate();
}
});
$("input:button").click(function() { // Button clicked?
validate();
});
});
function validate() {
if ($("#txtLogin").val()!='') {
document.cookie="loginID="+$("#txtLogin").val();
$("#lblError").hide();
$("form").attr("action","mainmenu.aspx"); // Change form action
$("form").submit(); // Submit the form
} else {
$("#lblError").show();
}
}
</script>
HTML
<form id="loginForm" runat="server">
<div>
<div class="theme login">
<p>Login</p>
<input type="text" id="txtLogin" maxlength="17" />
<div><input type="button" id="btnLogin" class="button" value="Log In" /></div>
<div id="lblError" style="display: none;">* You must enter a valid username</div> <!-- Error message -->
</div>
</div>
</form>

Categories

Resources