I'm creating a fake login experience in a pre-existing prototype. I think my problem is that there's already a click event on the button that advances it to the next div (it's a single page setup with divs that slide in) and I need to add the below validation functionality to the same button. Here's what I have so far:
$('#login_button').click(function(e){
var username_input = $('input[placeholder*="Hint"]'),
password_input = $('input[placeholder*="Password"]'),
username = $(username_input).val(),
password = $(password_input).val(),
login_errors = 0;
if ((username == '') || (password == '')) {
console.log("Please enter your username and password.");
login_errors = 1;
} else if ((username == 'my_username') && (password == 'my_password')) {
console.log("Username and password are correct.");
} else {
console.log("Your username or password are incorrect. Retry.");
login_errors = 1;
}
if (login_errors != 0){
e.preventDefault();
}
});
I'm getting a little lost there at the end. I can get the button to validate the input and to advance to the next page, but I don't know how to get it to do both of these things at the same time.
Here's my solution:
In my project, I had to refactor to sort out some logic. I made a fiddle that worked right away and helped clarify things for me:
jsfiddle.net/kapunahele/0c9htr4o
Related
It seems I'm having issues understanding exactly how form submission works...
Here is my event listener for submitting the from:
function createEventListeners() {
var orderForm = document.getElementsByTagName("form")[0];
if (orderForm.addEventListener) {
orderForm.addEventListener("submit", validateForm, false);
}//end if
else if (orderForm.attachEvent) {
orderForm.attachEvent("onsubmit", validateForm);
}//end else
}//end function createEventListeners()
Here is the code for validating the form:
function validateForm(evt){
var valid = true;
if (testLength(document.expReport.lname) == false){
valid = false;
}
if (testLength(document.expReport.fname) == false){
valid = false;
}
if (testLength(document.expReport.summary) == false){
valid = false;
}
if (testLength(document.expReport.init) == false){
valid = false;
}
//Call the testPattern() function with the department field for the field parameter.
if (testPattern(document.expReport.deptID, /DEPT\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the account field object for the field parameter.
if (testPattern(document.expReport.accID, /ACT\d\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the project field for the field parameter.
if (testPattern(document.expReport.projID, /PROJ-..-\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function for the ssn field
if ((testPattern(document.expReport.ssn, /\d\d\d\d\d\d\d\d\d/) || testPattern(document.expReport.ssn, /\d\d\d-\d\d-\d\d\d\d/)) == false){
valid = false
}
if (testDates() == false){
valid = false;
}
if (valid == false){
window.alert("Please fill out all required fields in the proper format.")
}
return valid;
}//end function validateForm(evt)
My issues is that even though the validate function is returning a false value the form submission still takes place.
I've done research on how to prevent this from being the case but it seems that most people just use the .preventDefaults() method to get around this. My issue is that the form that I'm working with contains text fields that are optional, thus if the user chooses to not fill them out, he will still be presented with a false return.
Is there an issue with how I'm setting up the listener for submission?
I've also tried to look up what can be done with the evt parameter but there is nothing there that is explaining why it refuses to function as intended.
The problem is that you're ultimately not doing anything with the validation result.
Your function validateForm will be getting invoked when the event fires, and it's probably working fine, but its return value goes nowhere.
Without seeing the whole page it's not possible to say what change you should make, but hopefully this is enough to shed light on what's needed so you can fix it.
I am doing password verification. I enter the password and then i re enter the password. But at every key press it gives me a tick mark sign which I dont want and also, even if I enter a wrong password it doesn't go the else part which gives the delete image. Can someone help me out. I am new at this.
function checkPasswordMatch() {
var password = $("#password").val();
var confirmPassword = $("#verifyPassword").val();
if (password != confirmPassword)
{
$("#marker").prepend('<img src="https://cdn3.iconfinder.com/data/icons/freeapplication/png/24x24/Apply.png" />');
}
else
{
$("#marker").prepend('<img src="https://cdn3.iconfinder.com/data/icons/musthave/16/Delete.png" />');
}
}
$(document).ready(function () {
$("#verifyPassword").keyup(checkPasswordMatch);
});
There are 2 problems with your approach.
First, to prevent the function to run at every keypress use the change event instead of keyup.
Second, I think you inverted the statement in the if, use == instead of !=
function checkPasswordMatch() {
var password = $("#password").val();
var confirmPassword = $("#verifyPassword").val();
if (password == confirmPassword){
$("#marker").html('<img src="https://cdn3.iconfinder.com/data/icons/freeapplication/png/24x24/Apply.png" />');
}else{
$("#marker").html('<img src="https://cdn3.iconfinder.com/data/icons/musthave/16/Delete.png" />');
}
}
$(document).ready(function () {
$(document).on('keyup','#verifyPassword', checkPasswordMatch );
});
edit: changed back the keyup event to match the request
To prevent this of happening each time you type somthing, you should change your event. I advise you to use the change event, at the passwords fields. See:
$(document).ready(function () {
$(document).on('change','#password, #verifyPassword', checkPasswordMatch );
});
I'm trying to display a warning message when a user types certain text into an input box. The problem is I only want to return false one time so the user can submit the form on the second click even if they don't change the text. I've tried adding a counter but jquery is not remembering the count on a second sumbit click. What is the best way to go about this?
if (email.val().indexOf("gmail") > -1))
{
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
return false;
}
I would use a flag to determine if they have already tried to submit, and if they haven't, then you give them the warning and return false:
var triedSubmit = false;
$(/* Your jQuery Object */).click(function() {
if (email.val().indexOf("gmail") > -1))
{
if (!triedSubmit){
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
triedSubmit = true;
return false;
}
}
}
Just set up some kind of flag
var flags = {}; // in some higher scope
// then later, in your verification function
if (email.val().indexOf("gmail") > -1 && !flags.warnedGmail) {
$('input[name=email]').css('border-color','red');
$("#submit").after('<p>Error - Do you want to use a gmail account?</p>');
flags.warnedGmail = true;
return false;
}
Why don't you put a class on your text box and remove it in the first failure? Thus when you look for it with jQuery a second time you won't be able to find it it and won't be able to apply the rule. I implmented it like so:
var submit = function()
{
var email = $('.emailFirstTry')
if (email.length > 0 && email.val().indexOf("gmail") > -1)
{
$('input[name=email]').css('border-color','red');
$("#submit").text('Error - Do you want to use a gmail account');
$('.emailFirstTry').removeClass('emailFirstTry');
return false;
}
$('input[name=email]').css('border-color','none');
$("#submit").text('Success!');
return true;
};
You can see it in action on this fiddle right here: http://jsfiddle.net/ozrevulsion/39wjbwcr/
Hope the helps :)
I have a form with some fields on. I am still learning Javascript. When my is submitted it triggers my JS which checks if the fields was submitted and then displays the errors in a which is done through innerhtml. Problem is it only display's the div for a few seconds and then finishes reloading the page and the div is not displayed anymore.
function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
}
}
You need to add
e.preventDefault();
for avoiding the default behavior.
Hence, if validation fails, the form won't be submitted.
please check whether your using normal HTML input element or ASP.NET server element. If your using Server element like then page will send back to server(reloaded) when click on button. the details you gave above is not enough.
you need to prevent the default behaviour if validation fails
you most likely do the validation on submit sth like:
$('form').submit(function(e){
check = checkradio() // let your function return true or false
if(!check){
e.preventDefault(); // add this to not submit the form
}
});
so the form will not submit if the validation fails
your tweaked validate function could look like this :
function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
return false;
}else {
return true;
}
}
I have a registration form split into blocks that was working perfectly using this code based on one of the examples from the website:
$('.register-next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
console.log('current block = ' + current);
console.log('next block = ' + next);
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
if (false === $('#form-register').parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
$('.block' + current)
.removeClass('show')
.addClass('hidden');
$('.block' + next)
.removeClass('hidden')
.addClass('show');
});
I then wanted to add an additional ajax validation to the last block of the code to make sure that the username was not already taken. I have the check working but the problems is that the form will now not submit when the validation checks are passed. Clicking on the submit button just calls the remote function again.
I am assuming that I have to reassign the function of the submit button once all validation checks have been made?
The ID username relates to the input field in the last block of my form.
Thanks
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
console.log("in 200");
return;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
I finally got this working. There is probably a far easier way to do it but this works.
firstly, I made one mistake with my code, I needed to return true if the status was 200
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
return true;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
I then added an additional piece of code to listen for the submit button to be clicked and remove parsley validation from the form before using javascript to submit
$('#new-user-submit').click(function(){
$('#form-register').parsley().asyncValidate()
.done(function(){
$('#form-register').parsley().destroy();
$('#form-register').submit(); });
});
I'm not a big user of javascript so it normally takes me a while to work my way through these things but I thought with parsley being so popular there would be far better support and documentation for it.