onbeforeunload not triggered properly - javascript

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;
});

Related

Form submit after preventDefault not working until click submit button

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);

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

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Form wont submit after correct email validation jquery

So my form throws up the correct error when no email is given. But when a correct email is put into the field, it wont submit. Where am I going wrong here? Thanks for any advice and help!
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$(document).ready(function(){
$("#submitbutton").click(function(e){
var none_answered = true;
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
}
else {
$('#email').removeClass('error');
return true;
}
});
});
<style type="text/css">
.error
{
color:red;
}
#texthere
{
color:red;
}
</style>
<body>
<form>
<label id="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="email"></br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
</body>
You have duplicate IDs, for the label and input field. Because of that the value of eMailToTest was always blank.
<label for="email" class="req"><span>*</span>Email:</label>
Demo: Fiddle
Try to do like this:
$("#submitbutton").click(function (e) {
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if (!myEmailRegEx.test(eMailToTest)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
$('form').submit();
}
});
Also, seem like your none_answered variable is redundant here.
Try this change id of label
<form action="http://www.utah.edu/">
<label class="req"><span>*</span>Email:</label> // Here duplicate id removed
<input id="email" class="req" name="email" value="" type="email">
</br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" />
</form>
Script
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#submitbutton").click(function(e){
e.preventDefault();
var none_answered = true;
var eMailToTest = $('#email').val();
if(!eMailToTest.match(myEmailRegEx)) {
none_answered = true;
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
console.log('if')
}
else {
console.log('else')
$('#email').removeClass('error');
$(this).closest('form').submit();
}
});
DEMO
You did a few mistakes.
Use event submit on forms (not click event)
You used id attribute on label and email. ID can be used only once on page.
var eMailToTest = $('#email').val();
It returned value of first element with ID email. So it's label (which has no value). You want input element instead.
Here is the working code.
HTML:
<form>
<label for="email" class="req"><span>*</span>Email:</label>
<input id="email" class="req" name="email" value="" type="text"><br>
<div id="texthere"></div>
<input id="submitbutton" type="submit" value="submit" formaction="http://www.utah.edu/">
</form>
Javascript:
var myEmailRegEx = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
(function(){
$("form").on('submit', function(e){
var eMailToTest = $('#email').val();
if(!myEmailRegEx.test(eMailToTest)) {
e.preventDefault();
$('#email').addClass('error');
$('#texthere').html("Please provide a correct email");
} else {
$('#email').removeClass('error');
}
});
})();
Also none_answered variable is redundant here.
Working example.
Hope this helps :)

Email validation + disable button

so i've done some code for contact form, but i have some problems to finish it up. So here is part of html contact form
<form action="" method="POST" name="contact-form" id="contact-us" >
<div class="form-group">
<input type="text" name="fullname" class="name send-check" placeholder="Name" tabindex="1" />
<input type="email" name="email" class="name send-check" id="email" placeholder="Email" tabindex="2" />
<div class="msg success error"> Incorrect e-mail </div>
<textarea rows="10" cols="45" name="msg" placeholder="Message" class="name send-check" tabindex="3"></textarea>
<a id="go" name="logo_order" href="#logo_order" rel="leanModal" disabled><button type="submit" id="btn-send" value="Отправить" disabled>Отправить</button>
<div id="logo_order">
Thank you for your message, window will close after 5 seconds.
</div>
</div>
</form>
When you type first time incorrect email at field (Email) it will write you with red color "Incorrect email", so then you re-write to your correct email and after that if you delete your correct email and type random letters it wil validate(it shouldn't) and disable button will become enabled, and also after that you click send, the modal appears and all form fields clears and enabled button becomes disable, but after that you type again in all three fields random text, the button will be enabled, so it's not doing validation at e-mail input
External code before /body to disable button, after click on Send
<script type="text/javascript">
$(document).ready(function () {
$('#btn-send').click(function () {
$('#contact-us').trigger("reset");
$('button:submit').attr("disabled", true);
});
});
</script>
Internal code
Validation
$('form input[name="email"]').blur(function () {
var email = $(this).val();
var valid = /(.+)#(.+)\.(com|edu|org|etc)$/;
if (valid.test(email)) {
$('.msg').fadeOut(500);
$('.success').fadeOut(500);
$(".send-check").each(function () {
$(this).keyup(function () {
$('#btn-send').prop('disabled', checkinput());
});
});
} else {
$('.error').fadeIn(500);
}
});
function checkinput() {
var valid = false;
$(".send-check").each(function () {
if (valid) { return valid; }
var input = $.trim($(this).val());
valid = !input;
});
return valid;
}
leanModal v1.1 | Ray Stone | Licensed under the MIT and GPL
(function($){$.fn.extend({leanModal:function(options){var defaults={top:100,overlay:0.5,closeButton:null};var overlay=$("<div id='lean_overlay'></div>");$("body").append(overlay);options=$.extend(defaults,options);return this.each(function(){var o=options;$(this).click(function(e){var modal_id=$(this).attr("href");$("#lean_overlay").click(function(){close_modal(modal_id)});$(o.closeButton).click(function(){close_modal(modal_id)});var modal_height=$(modal_id).outerHeight();var modal_width=$(modal_id).outerWidth();
$("#lean_overlay").css({"display":"block",opacity:0});$("#lean_overlay").fadeTo(200,o.overlay);$(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":o.top+"px"});$(modal_id).fadeTo(200,1);e.preventDefault()})});function close_modal(modal_id){$("#lean_overlay").fadeOut(200);$(modal_id).css({"display":"none"})}}})})(jQuery);
Timeout-modal
$(document).ready(function () {
$('#go').click(function (e) {
$('#logo_order, #lean_overlay').fadeIn(400, function() {
setTimeout(function () {
$('#logo_order, #lean_overlay').fadeOut(400);
}, 5000);
});
e.stopPropagation();
});
$(document).click(function (e) {
$('#logo_order, #lean_overlay').fadeOut(400);
});
});

Categories