I have the following input fields:
<input type="text" value="5" maxlength="12" id="qty" class="input-text qty" name="qty2050" tabindex="1">
and
<input type="text" value="0" maxlength="12" id="qty" class="input-text qty" name="qty2042" tabindex="1">
I use this code to prevent the user from losing inserted data (upon quitting the page):
<script>
window.onbeforeunload = function() {
var showAlert = false;
jQuery('.input-text.qty').each(function (){
//console.log("fonction 1");
var val = parseInt(jQuery(this).val(),10);
if(val > 0) { showAlert = true; }
//alert(val);
});
//console.log("fonction 2");
//console.log(showAlert);
if (showAlert == true) {
console.log("fonction 3");
return 'You have unsaved changes!';
}
}
</script>
I want to add an exception to my submit button, and to not show the alert message when there is a quantity > 0 in one of my input fields.
My problem is in adding this exception!
Thanks for help.
You can use bool confirmUnload. Like here: http://jonstjohn.com/node/23
<script>
var confirmUnload = true;
$("submit").click(function(){ confirmUnload = false; });
window.onbeforeunload = function() {
if (confirmUnload)
{
var showAlert = false;
jQuery('.input-text.qty').each(function (){
//console.log("fonction 1");
var val = parseInt(jQuery(this).val(),10);
if(val > 0) { showAlert = true; }
//alert(val);
});
//console.log("fonction 2");
//console.log(showAlert);
if (showAlert == true) {
console.log("fonction 3");
return 'You have unsaved changes!';
}
}
}
</script>
is this what you want:
<SCRIPT>
function checkForm(e) {
if (!(window.confirm("Do you want to submit the form?")))
e.returnValue = false;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm" action="0801.html"
onSubmit = "return checkForm(event)">
<INPUT type=submit>
</FORM>
your checks will go into the checkForm method in this case
Related
Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/
I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
I want to prevent the user from accessing the next page if there is an empty
inputField. The alert does show when the field is empty and i click the button, but i can click 'ok' and i get taken to the next page.
<script type="text/javascript">
window.onload = function(){
function checkFilled(inputField) {
if(inputField.value.length > 1) {
return true;
}
else {
alert('field1 is not filled in');
$("#button1").click(function(e){
e.preventDefault();
});
return false;
}
};
document.getElementById('button1').onclick = function() {
var field1 = document.getElementById('field1');
checkFilled(field1);
};
};
</script>
<input type="text" name="field1" id="field1"/>
<a href="nextpage.html">
<div id="button1"></div>
</a>
You used an a tag where the href attribute is set and gets you immediately to the next page, although the inputField is empty. This should do what you want:
window.onload = function(){
function checkFilled(inputField) {
if(inputField.value.length > 1) {
return true;
}
else {
alert('field1 is not filled in');
return false;
}
};
document.getElementById('button1').onclick = function() {
var field1 = document.getElementById('field1');
return checkFilled(field1);
};
};
<input type="text" name="field1" id="field1"/>
<form action="nextpage.html">
<input id="button1" type="submit" value="next">
</form>
Or if you prefer to use an a tag instead of a button:
function checkFilled() {
if(document.getElementById("field1").value.length > 1) {
window.location.href="nextpage.html";
}
else {
alert('field1 is not filled in');
return false;
}
}
<input type="text" name="field1" id="field1"/>
next
I would like to show my div when the email isn't validated. And hide it when it is.
This is what I tried, but it isn't working.
$("#fes-email").on("change.validation keyup.validation", function () {
var email = $(this).val();
$("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled')
$("#notification-container").show("slide");
});
}).trigger('change.validation');
You exit the function before you show it.
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled') <---exits function
$("#notification-container").show("slide"); <-- will never be called
});
AND you have a BIGGER problem. On every single change you are binding a submit handler to the form. That is BAD. Take the submit handler OUT of the change event.
(function() {
var isValid = false;
$("#fes-email").on("change.validation keyup.validation", function() {
var email = $(this).val();
isValid = email.length && isValidEmailAddress(email);
}).trigger('change.validation');
$('#fes-form').submit(function() {
if (isValid) {
$("#notification-container").slideUp();
} else {
$("#notification-container").slideDown();
}
return isValid;
});
}());
function isValidEmailAddress(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
#notification-container {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="fes-form">
<label for="fes-email">Email</label>
<input type="text" id="fes-email" name="fes-email" class="validation" />
<input type="submit" />
</form>
<div id="notification-container">Invalid Email</div>
I want to verify the checkboxes checked property. If any of them is not checked, display this sentence in span: "you should select one of them" and when I choose one of them, the message must disappear.
<form method="get"action="#" onsubmit="return vali();">
<span id="textspan" style="color:red"></span>
<input type="checkbox" class='gender' id="male">male
<input type="checkbox" class='gender' id="female">female
<input type="submit" class="validate" value="send" />
</form>
function vali() {
var bool = true;
var checkedCount = $('input[class="gender"]:checked').length;
if (checkedCount == 0) {
$("#textspan").html('select one of them');
bool = false;
}
if(checkedCount >= 1)
{
$("#textspan").html('');
bool = true;
}
return bool;
}
You did not add any function to the change (or click) event of your checkboxes:
your function 'vali()' is attached to form submit
It means your function will work only if you click on send button
So If you have your error, and you want to not have it when you click one of them(checkboxes), you have to add one function to that event:
function vali() {
var bool = true;
var checkedCount = $('input[class="gender"]:checked').length;
if (checkedCount == 0) {
$("#textspan").html('select one of them');
bool = false;
}
if(checkedCount >= 1)
{
$("#textspan").html('');
bool = true;
}
return bool;
}
$(".gender").click(function(){
var checkedCount = $('input[class="gender"]:checked').length;
if(checkedCount >= 1){
$("#textspan").html('');
}
});
as your click event is triggered whenever you click one of your '.gender', its better to have your function as:
$(".gender").click(function(){
$("#textspan").html('');
});
try below
<form method="get"action="#" onsubmit="return vali();">
<span id="textspan" style="color:red"></span>
<input type="radio" name="rad" class='gender' id="male">male
<input type="radio" name="rad" class='gender' id="female">female
<input type="submit" class="validate" value="send" />
</form>
<script>
$(document).ready(function(){
$(".gender").click(function(){
$("#textspan").html('');
});
});
function vali() {
var bool = true;
var checkedCount = $('input[class="gender"]:checked').length;
if (checkedCount == 0) {
$("#textspan").html('select one of them');
bool = false;
}
if(checkedCount >= 1)
{
$("#textspan").html('');
bool = true;
}
return bool;
}
</script>
fiddler like :- here