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
Related
Before clicking the button to execute, I want to verify whether the filled content meets the requirements. If there is any error message, the page cannot be redirected.
I used .preventDefault(), but it didn't work. Even error, the page was still redirected.
let btnAjtBtlCellier = document.getElementById('ajouterBouteilleCellier');
let fAjtBtlCellier = document.getElementById('form-ajouter-btl');
let inputEles = document.querySelectorAll('#form-ajouter-btl input');
let erreurAjtBtl = false;
inputEles.forEach(function(element) {
//Verify all required inputs
element.addEventListener('change', (evt) => {
quantiteValideAjt();
date_achatValideAjt();
prixValideAjt();
})
});
btnAjtBtlCellier.addEventListener('click', (evt) => {
erreurAjtBtl = false;
if (erreurAjtBtl) evt.preventDefault();
})
<div class="form-ajouter" id="form-ajouter-btl">
<p>Nom : <span data-id="" class="nom_bouteille"></span></p>
<span id="errNom_ajouter"></span>
<label for="millesime_ajouter">Millesime : </label>
<input type="text" name="millesime" id="millesime_ajouter" value="2020">
<label for="quantite_ajouter">Quantite : </label>
<input type="text" name="quantite" value="1" id="quantite_ajouter">
<span id="errQuantite_ajouter"></span>
<label for="date_achat_ajouter">Date achat : </label>
<input type="date" name="date_achat" id="date_achat_ajouter" value="">
<span id="errAchat_ajouter"></span>
<label for="prix_ajouter">Prix : </label>
<input type="text" name="prix" id="prix_ajouter" value="">
<span id="errPrix_ajouter"></span>
<label for="garde_jusqua_ajouter">Garde : </label>
<input type="text" name="garde_jusqua" id="garde_jusqua_ajouter">
<label for="notes_ajouter">Notes</label>
<input type="text" id="notes_ajouter" name="notes">
<!-- input caché avec id usager -->
<input type="hidden" name="courriel_usager" value="<?= $_SESSION[" courriel "] ?>">
</div>
<button name="ajouterBouteilleCellier" id="ajouterBouteilleCellier">AJOUTER LA BOUTEILLE</button>
You are setting the variable "erreurAjtBtl" on every click back to false, even if the input fields were validated successfully before. I would suggest to remove that line and set this variable in change-event like this:
element.addEventListener('change', (evt) => {
if (quantiteValideAjt() && date_achatValideAjt() && prixValideAjt())
erreurAjtBtl = false;
else
erreurAjtBtl = true;
})
I've assumed that validation functions return true or false.
Assuming that
quantiteValideAjt();
date_achatValideAjt();
prixValideAjt();
all return false if errors, and true if valid, you need to do
btnAjtBtlCellier.addEventListener('click', (evt) => {
const erreurAjtBtl = !quantiteValideAjt() || !date_achatValideAjt() || !prixValideAjt();
if (erreurAjtBtl) evt.preventDefault();
})
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.
I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
<label for="email">Email Address</label>
</div>
<br></br>
<a class="waves-light btn red lighten-2 disabled" id="submit">Submit
<i class="material-icons right">send</i>
</a>
<br></br>
<br></br>
<br></br>
</form>
Here is the JavaScript/jQuery:
$(document).ready(function(){
$('.parallax').parallax();
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});
function checkValidity (current) {
let isValid = true;
if (!current.val()) {
isValid = false;
} else {
isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
submit.removeClass('disabled');
} else {
if (!submit.hasClass('disabled')) {
submit.addClass('disabled');
}
}
}
function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});
Please let me know what I'm doing wrong! Thanks!
You can use email type for your input and a button submit who will trigger validation input.
I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? )
You have to add jQuery Validation Plugin
$(document).ready(function(){
$('#survey input').on('keyup', function(){
var validator = $("#survey").validate();
if (validator.form() && validateEmail($('#email').val())) {
$('#submitButton').prop('disabled', false);
$('#submitButton').removeClass('disabled');
}
else{
$('#submitButton').prop('disabled', true);
$('#submitButton').addClass('disabled');
}
} );
function validateEmail(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.toLowerCase());
}
/*
Confirmation Window
*/
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
<label for="email">Email Address</label>
</div>
<button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
</form>
StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen
Another way to solve this is to add a regex field to your <input ... elements e.g.
<div class="input-field col s6">
<input id="email" type="text" class="validate" value="hello#email.com" regex="(?!.*\.\.)(^[^\.][^#\s]+#[^#\s]+\.[^#\s\.]+$)" required="" aria-required="true" value="hello#email.com" >
<label for="email">Email</label>
<span class="helper-text" data-error="Invalid email address."></span>
</div>
The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.
name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
age (only contain numbers - regex = ^\d+$).
NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.
To validate using e.g. JQuery - you would add listeners to each of your input elements: -
$(document).ready(function(){
$("input").on('input propertychange blur', function(event) {
var elm = event.currentTarget;
var val = elm.value;
var isValid = true; // assume valid
// check if required field
if (elm.hasAttribute("required")) {
isValid = val.trim() !== '';
}
// now check if regex
if (isValid && elm.hasAttribute("regex")) {
var regex = new RegExp(elm.getAttribute("regex"), 'g');
isValid = regex.test(val);
}
elm.classList.remove(isValid ? "invalid" : "valid");
elm.classList.add(isValid ? "valid" : "invalid");
updateButtonState();
});
});
function updateButtonState () {
var numOfInvalid = $('input.invalid').length;
if (numOfInvalid > 0) {
$('.submit-button').prop('disabled', true);
$('.submit-button').addClass('disabled');
}
else{
$('.submit-button').prop('disabled', false);
$('.submit-button').removeClass('disabled');
}
}
When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.
If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).
See the following CodePen to see everything in action: -
https://codepen.io/bobmarks/pen/oNGGvWq
I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
I have a login form.
Field: Username textbox, password text box, 2 check boxes, submit button--- everything inside a form.
submit button initially disabled. It is enabled only when username, password or AT LEAST any one checkbox is checked. button gets enabled when username & password fields are entered. no change happens even if checkbox is checked or unchecked.
<form class="form-horizontal" role="form" action="page2.html">
<div class="form-group">
<label for="txtusername" class="col-sm-4 control-label ">Username</label>
<div class="col-sm-8">
<input type="text" class="form-control textboxprop" id="txtusername" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="txtpassword" class="col-sm-4 control-label ">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control textboxprop" id="txtpassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<div class="checkbox">
<input id="chk" type="checkbox" >chk1
<input id="chk" type="checkbox" >chk2
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="signin" class="btn btn-default" disabled>Sign in</button>
</div>
</div>
</form>
This is the form. Below given is the javascript function I use.
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
You need to listen checkboxes change event too. Try this code:
var $input = $('input'),
$check = $input.filter(':checkbox'),
$register = $('#signin');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$check.filter(':checked').length);
});
Demo: http://jsfiddle.net/jy3UR/1/
Your HTML is invalid. A <label> is closed which wasn't started and you have a duplicate ID 'chk'...
You need to put it in the onload event of the document and indeed as #dfsq already stated, you need to add a check for the checkboxes too, like so:
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$chk = $('input[type=checkbox]');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$chk.filter(':checked').length);
});
})
otherwise it will get executed when the DOM has not fully loaded yet and your fields will not be available...
DEMO
First of all you have used same id for both the check box.
rename it like below
<input id="chk1" type="checkbox" >chk1</label>
<input id="chk2" type="checkbox" >chk2</label>
and modify your code like below :
<script>
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
var checked = $("input[type='checkbox']:checked");
if(checked.length >0) // check if atleast one checkbox checked
trigger = true;
if(!trigger){
if(!$(this).val()) {
trigger = true;
}
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
</script>
You should try this simple solution :
jQuery(function($) {
$('form input').on('change',function() {
isDisabled = !(($('#txtusername').val().length > 0 && $('#txtpassword').val().length > 0) || $('input[type="checkbox"]:checked').length > 0);
$('#signin').attr('disabled', isDisabled);
});
});
It does its job.