Form submit after preventDefault not working until click submit button - javascript

I have a Login form that working fine. I tried to extend login action for adding extra features.
First I prevent the form to be submit when the submit button is clicked, I perform ajax request and finally if everything is correct I submit the form, but my form is not submitted until the submit button is clicked twice. What am I doing wrong?
HTML Part:
<div id="loginFormDiv">
<form class="form-horizontal" method="POST" action="index.php">
<input type="hidden" name="module" value="Users">
<input type="hidden" name="action" value="Login">
<div class="group"><input id="username" type="text" name="username" ><span class="bar"></span><label>Username</label></div>
<div class="group"><input id="password" type="password" name="password" ><span class="bar"></span><label>Password</label></div>
<div class="group"><button type="submit" class="button buttonBlue">Sign in</button></div>
</form>
</div>
JS Part:
jQuery.Class("ParsSecureLogin_Js", {}, {
checkLogin: function () {
var thisInstance = this;
var checkUserLogin = function (e) {
e.preventDefault();
var username = $('#username').val();
var user_pass = $('#password').val();
var theForm = $(this);
var url = 'index.php?module=ParsSecureLogin&parent=Settings&action=CheckLogin&_user=' + username + '&_pss=' + user_pass;
jQuery.ajax({
url: url
}).done(function (data) {
if (data == '' || data == 'undefined') {
alert('Unknown error. Please contact admin to check!');
return false;
} else {
theForm.unbind('submit').submit();
return true;
}
});
}
jQuery('#loginFormDiv').on("submit", checkUserLogin);
},
registerEvents: function () {
var thisInstance = this;
thisInstance.checkLogin();
}
});
jQuery(document).ready(function () {
var ParsSecureLogin = new ParsSecureLogin_Js();
ParsSecureLogin.registerEvents();
});

It is because #loginFormDiv is a <div> not a <form> change the selector to:
jQuery('#loginFormDiv form').on("submit", checkUserLogin);

Related

Another scripts onclick function is not getting triggered when I use form.submit(), form.requestSubmit(submitBtn) or submit.click() programatically

In the script contact_form_2.js a member of our team created a submitbtn.onclick function that handles the recaptcha interaction on all forms used on our platform.
I am working on creating a new lead form that looks for URL params in the URL, and when all of them are present and added into the form it auto submits that form.
Whenever I auto submit the form though, the contact_form_2.js onclick method does not get triggered. I've tried every way I can to submit the form programmatically, and none of the methods work. How can I get contact_form_2.js's onclick to trigger when I submit my new form programmatically in myscript.js?
contact_form_2.js
window.addEventListener("load", function () {
var submitbtn = document.querySelector(`form[name=contactform] button#submit`) || document.querySelector(`form[name=contactform] button[name=submit]`);
submitbtn.style.display = "none";
var lib = document.createElement("script");
lib.async = true;
lib.defer = true;
lib.src = "https://www.google.com/recaptcha/api.js?render=key-here";
document.body.appendChild(lib);
lib.onload = function () {
console.log("recaptcha loaded");
submitbtn.style.display = "block";
var cform = document.querySelector("[name=contactform]");
submitbtn.onclick = function onSubmit(e) {
e.preventDefault();
grecaptcha.ready(function () {
grecaptcha.execute("key-here", {
action: "submit",
}).then(function(token) {
var cform = document.querySelector("[name=contactform]");
var recap = document.createElement("input");
recap.type = "hidden";
recap.name = "g-recaptcha-response";
recap.value = token;
cform.appendChild(recap);
setTimeout(function () {
document.createElement("form").submit.call(cform);
});
});
});
}
};
});
myscript.js
window.addEventListener("load", function() {
var basicJunkForm = document.querySelector('#basic-junk-form');
document.createElement('form').submit.call(basicJunkForm);
//Other attempts:
/*
var submit = basicJunkForm.querySelector("#submit");
basicJunkForm.requestSubmit(submit);
*/
//basicJunkForm.submit(); (doesn't work because my submit button is named submit, which is why I do the active work around.)
});
myform.html
<form method="POST" action="/cp/resources/lib/contact_form.php" id="basic-junk-form" name="contactform" class="contactform contact-2">
<div class="form-group">
<input type="hidden" name="subject" id="subject" value="DRS: New Junk Removal Lead">
<input type="hidden" name="message" id="message" value="New Junk Removal Lead">
<input type="text" name="name" id="name" class="form-control" placeholder="Full Name">
<input type="email" name="email" id="email" class="form-control" placeholder="E-mail">
<input type="phone" name="phone" id="phone" class="form-control" placeholder="Phone">
<input type="text" name="zip" id="zip" class="form-control" placeholder="Zip">
<button id="submit" class="btn btn-primary btnbdr btn-lg btn-block g-recaptcha" data-loading-text="Loading..." data-sitekey="6Lf7mtUZAAAAALRdG-q8KnHw9dh3ZZSxGMNz8zg1" data-callback="onSubmit" data-action="submit">
<i class="fa fa-send"></i> Send Message
</button>
</div>
</form>
<script src="/cp/resources/js/contactform_2.js?0febd418e98f68a4f38e261004f53515" async="" defer=""></script>
<script src="/view/assets/junk_form_basic.js"></script>
Edit: Also tried this as per CherryDT's recommendation
window.addEventListener("load", function() {
var basicJunkForm = document.querySelector('#basic-junk-form');
simulateFormSubmission();
function simulateFormSubmission() {
const event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
const submitButton = basicJunkForm.querySelector("#submit");
const cancelled = !submitButton.dispatchEvent(event);
if(cancelled) {
console.log('cancelled');
}
}
});

How would you make an iframe if the value is true in javascript?

I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Automatic Login Using JavaScript not Working Properly

I would like it such that a user only has to sign-in once and then the next time they open the hybrid app the get signed in automatically. The JavaScript code below here works but only when I remove the 'login/submit' div () which I need. How can I get around this?
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
#chiboz in your javascript, instead of using:
document.EventConfirmRedirection.submit();
use:
$('#submit').click();

onbeforeunload not triggered properly

I can't figure out why the script isn't working with the form. Why doesn't the $("form").submit(function() call the form with id form? This script isn't even performing the window.onbeforeunload so I guess the script is faulty. Does anyone know what's wrong?
<form id="formID" class="access_form" name="form" method="post" action="site.com">
<div class="row">
<label for="email">Email Address:</label>
<input class="txt_email" type="text" id="email" name="email" value="" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" />
</div>
<div class="row">
<input type="submit" class="btn_access" value="Get Immediate Access" name="submit1" />
</div>
</form>
JavaScript:
var formHasChanged = false;
var submitted = false;
$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form
select, form.confirm-navigation-form textarea', function (e) {
formHasChanged = true;
});
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (formHasChanged && !submitted) {
var message = "Please enter your email", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("#formID").submit(function () {
submitted = true;
});
});
just try this.The id of the form is form itself.So select the form like this using jQuery
$("#form").submit(function () {
submitted = true;
});
OR
Or try giving another id for the form for example "formID".Then select using that id like this.
$("#formID").submit(function () {
submitted = true;
});

Categories