am working in a popup when we click login a popup opens with fields !!! i want to check username and password with database before login button fired.. used ajax with keyup function for password field!
but keyup is firing for every character typed in password field... but the requirement is after typing password field ajax should be called and result should be displayed... is there any alternative for keyup?
now am getting as "wrong password for every character typed" and after entring correct password it will login,... but i want to show error as wrong password when user completely enters password (if password is wrong)
<script type="text/javascript">
$(document).ready(function() {
$("#upwd").change(function()
//$('#upwd').on('input', function()
//$('#upwd').keyup(_.debounce(doSomething , 500), function() {
var upwd = $("#upwd").val();
var uemail = $("#uemail").val();
var msgbox = $("#status");
//alert(uemail);
//alert(upwd);
//setTimeout(function() {
//if($('#upwd').val() == upwd){
$.ajax({
type: "POST",
url: "checkl_login.php",
data: "uemail="+ uemail,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK') {
msgbox.html(msg);
//return false;
} else {
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
error displayed in status id in span......
checkl_login.php code is aalso perfect.....
Try using .focusout() event as shown :-
$("#upwd").on("focusout",function(){
//..your code..
});
and in addition of these events ,use a login button also and check validations on the click of the button.
Use the change event instead of keyup.
IMHO it's better:
to use keyup (it allows to handle any keyboard changes. For example, removing the symbol by backspace)
to handle 'paste' (because user may copy/paste password but not type it)
to validate password if user does not press a key during some period of time (for example, within 1 second) - setTimeout and clearTimeout should help
to abort ajax request if user starts to type when ajax request is in progress
I.e. you may try something like the following:
$(document).ready( function() {
var ajax_h;
var delayMilliseconds = 1000; // i.e. = 1 second
var timeoutId;
function checkAuth() {
if (ajax_h) {
ajax_h.abort();
}
ajax_h = $.ajax(
// PUT YOUR CODE HERE
);
}
$("#upwd").on('keyup paste', function () {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(checkAuth, delayMilliseconds);
});
});
Related
I have the very simple code below that installs an event handler on confirmPass keystrokes. On registration form submit I want to be able to disable the submit if the passwords do not match. In the 'onClick' event for the registration form if I call confirmPass() it fails to submit, if I comment it out it submits. Why is confirmPass() blocking the programatic form submit?
$( document ).ready(function() {
console.log( "ready!" );
$('#confirmPassword').keyup(function(){
confirmPass();
})
});
function registrationSubmit(){
confirmPass();
$('#registration').submit();
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (!(pass == cpass)) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
$('#registration').submit(function (event) {
event.preventDefault();
});
return;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!")
}
this line adds an event handler.
$('#registration').submit(function (event) {
event.preventDefault();
});
Which means every time the submit event is fired after this line have been hit it will be cancelled. Since you call confirmPass on each keystroke the line will be executed at least once and thus submits events on the form will always be cancelled. Instead you might want to only call submit only if the validations are succesfull and remove the line I mentionned above
Exemple
function registrationSubmit(event){
// Assuming you modify confirmPass to return true/false
if(confirmPass()){
$('#registration').submit();
}
}
You never remove the submit handlers that call preventDefault().
Instead of adding a handler in confirmPass(), check whether the password is valid in registrationSubmit(). Have confirmPass() return a boolean to indicate this.
$(document).ready(function() {
console.log("ready!");
$('#confirmPassword').keyup(function() {
confirmPass();
})
});
function registrationSubmit() {
if (confirmPass())
$('#registration').submit();
}
}
function confirmPass() {
var pass = $('#password').val();
var cpass = $('#confirmPassword').val();
if (pass != cpass) {
$('#confirmPassword').addClass('text-danger');
$('#cpassmsg').addClass('text-danger').removeClass('ui-helper-hidden');
$('#cpassmsg').text("Confirm Password Fails")
return false;
} else {
$('#confirmPassword').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').addClass('text-success').removeClass('text-danger');
$('#cpassmsg').text("Confirm Password Match!");
return true;
}
}
I'm putting together a Flask web app as a final project for a course, and I'm struggling to fix some JavaScript for the site's registration form.
I have two independent bits of code, one from Bootstrap to validate form completeness:
<script>
(function()
{
'use strict';
window.addEventListener('load', function()
{
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form)
{
form.addEventListener('submit', function(event)
{
if (form.checkValidity() === false)
{
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
and one that I customized to check that the user is registering a unique username. If the username is not unique, it populates an innerHTML error to a "user_result" div tag beneath the username form field:
<script>
// set input value to form entry for username
let input = document.getElementById('user');
// on key up, run check
input.onkeyup = function()
{
// query to check username against database
$.get('/check?username=' + input.value, function(data)
{
// if check query returns False, username is NOT available
if (!data)
{
// put notification text into result tag above
document.getElementById('user_result').innerHTML = 'Username unavailable.';
// prevent form submission via register button
document.getElementById('register').addEventListener("click", function(event)
{
event.preventDefault();
});
}
// if check query returns True, username is available
if (data)
{
// no notification text required
document.getElementById('user_result').innerHTML = '';
// allow form submission by unbinding event handler
document.getElementById('register').addEventListener("click", function(event)
{
event.unbind();
});
}
});
};
</script>
Individually, each seems to work okay, but:
I can't seem to put both scripts in the same HTML doc without unexpected behavior (e.g. the form won't submit, but no error messages show, or the form submits despite a bad username.)
I'd really like for the "Username unavailable." message to display in the same style of the "invalid-feedback" class used for the Bootstrap form validation.
I'd even be fine checking for the username availability upon submit (see below attempt) instead of upon keyup, but I'd ideally check username validity before form submission.
Here is one of my attempts to stitch the code pieces together. The result here unfortunately is that the Bootstrap validation works, but the username check is ignored (I can submit the form with a bad username and instead of the JS blocking the form submission, it goes through).
<script>
(function()
{
// set input value to form entry for username
let input = document.getElementById('user');
'use strict';
window.addEventListener('load', function()
{
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form)
{
form.addEventListener('submit', function(event)
{
if (form.checkValidity() === true)
{
(function()
{
$.get('/check?username=' + input.value, function(data)
{
// if check query returns False, username is NOT available
if (!data)
{
// put notification text into result tag above
document.getElementById('user_result').innerHTML = 'Username unavailable.';
// prevent form submission via register button
document.getElementById('register').addEventListener("click", function(event)
{
event.preventDefault();
event.stopPropagation();
});
}
// if check query returns True, username is available
if (data)
{
// no notification text required
document.getElementById('user_result').innerHTML = '';
// allow form submission by unbinding event handler
document.getElementById('register').addEventListener("click", function(event)
{
event.unbind();
event.stopPropogation();
});
}
});
});
}
if (form.checkValidity() === false)
{
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
Can someone help me understand where my thinking is wrong? Please let me know if it'd be helpful to see the HTML form or Flask code for the username check.
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 have textarea and I want to detect when the user will finish TYPING or PASTING a url. I want to catch that url an send it to php.
I looked at many solutions from google, but they all seems to add a anchor tag around the link which I don't want to do.
I tried using this regexp I found in a solution on this website, but it did not work:
/(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
the problem with it is that as soon I type something like http://, it will automatically send that string only.
I don't want to write a regexp with finite list of TLDs. What ways can I archive this?
this is the code:
$(document).ready(function() {
$('#write-post-textarea').keyup(function() {
if(isUrl($(this).val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
});
function isUrl(s) {
//var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
});
Use keyup event along with keycode validation to make sure enter or space button pressed before start validation.
$("#write-post-textarea").keyup(function (e) {
if (e.which == 13 || e.which == 32) { // 32 may be for space bar click
if(isUrl($(this).val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
}
});
I think the problem you have is that whenever you press a key it checks url once. So as soon as you type in something that matches the regexp it sends. You can try set a timer like this:
var timer;
$(document).ready(function() {
$('#write-post-textarea').keyup(function() {
var $this = $(this);
clearTimeout(timer);
setTimeout(function ()}
if(isUrl($this.val())){
//Show the url in an alert box
alert($(this).val());
}else{
//do something if its not a url
}
}, 2000);
});
function isUrl(s) {
//var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
});
So that timer will be clear when you are typing, and only run the code when you stop.
What I'm trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.
I've managed to get the OnBeforeUnload() dialog to pop-up... but I don't want it to be displayed at all if the user hasn't modified any field values. For this, I'm using this hidden input field called is_modified that starts with a default value of false and flips to true when any field is edited.
I tried to bind the change event to this is_modified field to try and detect for value change... and only then activate OnBeforeUnload.
$( '#is_modified' ).change( function() {
if( $( '#is_modified' ).val() == 'true' )
window.onbeforeunload = function() { return "You have unsaved changes."; }
});
But from what I figure is that the change() event works only after these 3 steps - a field receives focus, a value is changed and the field looses focus. In case of the hidden input field, I'm not sure how this receiving and loosing focus part works! Hence, the onbeforeunload function is never being activated.
Can anyone suggest a way to maintain a trigger over is_modified?
Thanks.
I had a similar requirement so came up with following jQuery script:
$(document).ready(function() {
needToConfirm = false;
window.onbeforeunload = askConfirm;
});
function askConfirm() {
if (needToConfirm) {
// Put your custom message here
return "Your unsaved data will be lost.";
}
}
$("select,input,textarea").change(function() {
needToConfirm = true;
});
The above code checks the needToConfirm variable, if its true then it will display warning message.
Whenever input, select or textarea elements value is changed, needToConfirm variable is set to true.
PS: Firefox > 4 don't allow custom message for onbeforeunload.
Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=588292
UPDATE: If you are a performance freak, you will love #KyleMit's suggestion.
He wrote a jQuery extension only() which will be executed only once for any element.
$.fn.only = function (events, callback) {
//The handler is executed at most once for all elements for all event types.
var $this = $(this).on(events, myCallback);
function myCallback(e) {
$this.off(events, myCallback);
callback.call(this, e);
}
return this
};
$(":input").only('change', function() {
needToConfirm = true;
});
The following works well in jQuery:
var needToConfirm = false;
$("input,textarea").on("input", function() {
needToConfirm = true;
});
$("select").change(function() {
needToConfirm = true;
});
window.onbeforeunload = function(){
if(needToConfirm) {
return "If you exit this page, your unsaved changes will be lost.";
}
}
And if the user is submitting a form to save the changes, you might want to add this (change #mainForm to the ID of the form they're submitting):
$("#mainForm").submit(function() {
needToConfirm = false;
});
We just use Window.onbeforeunload as our "changed" flag. Here's what we're doing, (using lowpro):
Event.addBehavior({
"input[type=radio]:change,input[type=text]:change,input[type=checkbox]:change,select:change": function(ev) {
window.onbeforeunload = confirmLeave;
}
".button.submit-button:click": function(ev) {
window.onbeforeunload = null;
},
});
function confirmLeave(){
return "Changes to this form have not been saved. If you leave, your changes will be lost."
}
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works For me.
Try your logic in a different manner. Meaning, put the logic for checking the value of the input field in your onbeforeunload method.
window.onbeforeunload = function () {
if ($("#is_modified").val() == 'true') {
return "You have unsaved changes.";
} else {
return true; // I think true is the proper value here
}
};
in IE9 you can use simple return statement (re) which will not display any dialogue box. happy coding..
why not have the onbeforeunload call a function that checks if the values have changed, and if so return the "unsaved changes" confirm?