I have a form, on the first 3 input fields (fname, lname, addr) there is an onkeyup function which checks the inputs value against a database. If there is a single match, the function offers a popup (javascript confirm) which asks if the record in the database is correct, if so will prepopulate the fields.
Problem is, most people can type faster than the function can check. If the function finds a match with "smi" but the users types "smith" before the pop up, then the confirm will appear 3 times consecutively.
What can be done about this?
Here's what I've tried, no luck
function startAjax(){
if(document.getElementById("flag").value == "yes"){
if (window.XMLHttpRequest){ xmlhttpp=new XMLHttpRequest(); }else{ xmlhttpp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttpp.onreadystatechange=function(){
if(xmlhttpp.readyState==4 && xmlhttpp.status==200){
var status = xmlhttpp.responseXML.getElementsByTagName('status')[0].firstChild.nodeValue;
var fname = xmlhttpp.responseXML.getElementsByTagName('fname')[0].firstChild.nodeValue;
var addr = xmlhttpp.responseXML.getElementsByTagName('addr')[0].firstChild.nodeValue;
var lname = xmlhttpp.responseXML.getElementsByTagName('lname')[0].firstChild.nodeValue;
var city = xmlhttpp.responseXML.getElementsByTagName('city')[0].firstChild.nodeValue;
var state = xmlhttpp.responseXML.getElementsByTagName('street')[0].firstChild.nodeValue;
var zip = xmlhttpp.responseXML.getElementsByTagName('zip')[0].firstChild.nodeValue;
var email = xmlhttpp.responseXML.getElementsByTagName('email')[0].firstChild.nodeValue;
document.getElementById("ajax_status").innerHTML=status;
if(status == "Found user"){
document.getElementById('pop_display').style.display = "block";
var confirmMsg = "*User Found*\n\nName: "+fname+" "+lname+"\nAddress: "+addr+"\nCity: "+city+"\nState: "+state+"\nZip: "+zip+"\nEmail: "+email+"\n\nClick 'OK' To populate fields or click 'Cancel' if this is not the correct info.";
var fillOrNot = confirm(confirmMsg);
if(fillOrNot === true){
document.getElementById('fname').value = fname;
document.getElementById('lname').value = lname;
document.getElementById('address').value = addr;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
document.getElementById('zip').value = zip;
document.getElementById('email').value = email.trim();
document.getElementById('flag').value="no";
}else{
document.getElementById('flag').value="yes2";
document.getElementById("ajax_status").innerHTML="Aborted";
}
document.getElementById('pop_display').style.display = "none";
}
}
}
var param1 = document.getElementById('fname').value;
var param2 = document.getElementById('lname').value;
var param3 = document.getElementById('address').value;
var url = "https://www.mywebsite.com/ajaxhandler.php?fname="+param1+"&lname="+param2+"&addr="+param3;
xmlhttpp.open("GET",url,true);
xmlhttpp.send(null);
}
}
Use 'blur' of javascript or 'onfocusout' of jQuery instead of 'onkeyup'
Add a variable outside startAjax, like 'checking', that you will set to 'true' when you are waiting for the response from database - once you receive the responce, set it to 'false.' Then, in the point of your code where you're calling the database, check whether or not you're already waiting for a responce (if you are, just skip the call altogether)
It also helps to delay the first call by a bit, like 100 milliseconds, so the user can enter a couple of characters before it - javascript's timeout will do the job.
Related
I have been working on a project where we can store login info so that once a user registers, the data gets saved in the localStorage object. I have mentioned some javascript code to show that:
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
function register() {
localStorage.setItem("username", user.value);
localStorage.setItem("password", pass.value);
localStorage.setItem("email", email.value);
document.getElementById("id01").innerHTML = "Registration successful";
}
function login() {
var checkuser = localStorage.getItem("username");
var checkpass = localStorage.getItem("password");
if (checkuser === user2.value && checkpass === pass2.value) {
document.getElementById("demo").innerHTML = "You are now logged in.";
} else {
document.getElementById("demo").innerHTML = "Incorrect username and password";
}
}
In the javascript code mentioned above, i have used the localStorage object to store the values. I have stored the username in a user property, the password in a pass property and the email in an email property.
My question is: Is there any way where we can store the username, password and the email in one property(user property)?
Yes, you can do this by putting all the features you want in one object.
Example here
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var email = document.getElementById("email");
var user2 = document.getElementById("user2");
var pass2 = document.getElementById("pass2");
var user = {
email:email,
pass:pass,
//.. other properties
}
then you can set like this
localStorage.setItam("USEROBJ",JSON.stringify(user));
When you want to call this you should use like
var user = JSON.parse(localStorage.getItam("USEROBJ"));
By the way you can read this
Storing Objects in HTML5 localStorage more detail about you question
You can store JSON as a string in localStorage property and then parse it
function setUser() {
localStorage.setItem('user', JSON.stringify(user));
}
function getUser() {
user = JSON.parse(localStorage.getItem('user'))
}
I'm working on creating a basic messenger using Javascript. I have three functions in a separate js file called loadMessage, messageListener, and displayMessage.
The function loadMessage makes a call to my database for all existing messages, and then calls displayMessages to construct some divs which I use to show the messages I got from the server. These divs are created to appear under each other, with the bottom div being the newly created one showing the latest message.
Once all the messages have been created loadMessage then calls messageListener. This function 'listens' for any new messages which might appear on the database. If any appear then messageListener calls displayMessage. I expect this to create a new div at the bottom of my other divs as before, however when it calls displayMessage the behaviour is completely different than when loadMessage calls displayMessage.
Specifically, it does not create a new div but instead just changes the text in an existing div which appears anywhere within the newly created divs (for example, the div which displays the first message or one somewhere in the middle).
My HTML and PHP files all behave as expected, so I think my issue is somewhere in these three functions.
How can I fix this to behave as expected?
Code:
// Loads chat messages history and listens for upcoming ones.
function loadMessages(userID, contactID) {
contactIDGlobal = contactID;
//load existing messages
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var param = "userID="+userID+"&contactID="+contactID+"&date="+date;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Interface-getMessage.php?", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(param);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//retrives a string of all past messages
var messageString = xmlhttp.responseText;
//parse string to get messages.
var parseMessageString = messageString.split('-');
for (var i = 0; parseMessageString[i] !== null && parseMessageString[i] !== ''; i = i+5){
var contactID = parseMessageString[i];
var senderID = parseMessageString[i+1];
var message = parseMessageString[i+2];
var time = parseMessageString[i+3];
var mID = parseMessageString[i+4];
displayMessage(userID, senderID, contactID, message, date, time, mID);
}
}
};
//listen for new messages
messageListener(userID, contactID);
}
function messageListener(userID, contactID){
if(typeof(EventSource)!=="underfined") {
var newMessage = new EventSource("testerfile.php?userID="+userID+"&contactID="+contactID);
newMessage.onmessage = function(event) {
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3];
var time = parseNewMessage[4];
var messageID = parseNewMessage[5];
console.log(event.data);
displayMessage(userID, senderID, contactID, message, date, time, messageID);
};
}else {
document.getElementById("messages").innerHTML = "Your browser does not support this";
}
}
// Displays a Message in the UI.
function displayMessage(userID, senderID, contactID, nMessage, date, time, id){
var messageListElement = document.getElementById('messages');
var messageInputElement = document.getElementById('message');
// If an element for this message already exists, then get it
var id = id;
var div = document.getElementById(id);
// If an element for that message does not exists yet we create it.
if (!div) {
var container = document.createElement('div');
if (userID == senderID){
container.innerHTML = SENDER_MESSAGE_TEMPLATE;
}else{
container.innerHTML = MESSAGE_TEMPLATE;
}
div = container.firstChild;
div.setAttribute('id', id);
for (var i = 0; i < messageListElement.children.length; i++) {
var child = messageListElement.children[i];
}
messageListElement.insertBefore(div, child);
}
var messageElement = div.querySelector('.message');
messageElement.textContent = nMessage;
// Replace all line breaks by <br>.
messageElement.innerHTML = messageElement.innerHTML.replace(/\n/g, '<br>');
}
// Template for messages.
var SENDER_MESSAGE_TEMPLATE =
'<div class="sender_message-container">' +
'<div class="message"></div>' +
'</div>';
var MESSAGE_TEMPLATE =
'<div class="message-container">' +
'<div class="message"></div>' +
'</div>';
The problem was coming from the date being returned as y-m-d, and the parser using "-". This mean I was creating a time var which was the month of my date, and the message ID as the day. I made the alteration below to fix this...
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3]+"-"+parseNewMessage[4]+"-"+parseNewMessage[5];
var time = parseNewMessage[6];
var messageID = parseNewMessage[7];
function myFunction() {
var showpass = document.getElementsByClassName('lpass');
if (showpass.type === "password") {
showpass.type = "text";
} else {
showpass.type = "password";
}
}
This script is not working. In console.log('') it is skipping to else condition directly.
Your var showpass = document.getElementsByClassName('lpass'); returns an array so use the 0 index to get the first match.
var showpass = document.getElementsByClassName('lpass')[0];
You can see more about the function here, https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.
I'm trying to make a page out of javascript. I'm pretty new to all this, so bear with me.
I have a form, and when you press submit I have the following bit to see if the fields are left blank:
function calculatePrice()
{
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var norepeat = false;
if (norepeat==false && (GasPrice =="" || Distance =="" || Mileage ==""))
{
var para=document.createElement("p");
para.setAttribute("class", "error");
var node=document.createTextNode("All fields must be completed");
para.appendChild(node);
var element=document.getElementById("content");
element.appendChild(para);
var norepeat = true;
}
I created the error as a paragraph tag that appears. The problem is that when I press submit more than once, it writes the error message every time. I tried the norepeat variable thing, but it doesn't seem to be working. Any help?
Though I'm not completely sure your intentions, it'd have to look something more like:
var norepeat = false;
function calculatePrice() {
if(!norepeat && (/* other conditions here */)) {
norepeat = true;
}
return !(/* other conditions above */);
}
Where norepeat is defined in a global scope. Also, remember to use === as opposed to ==. And trimming the string before testing it wouldn't be a horrible idea...
But, wouldn't you want the errors to still persist if the user hasn't corrected them - isn't that the point of validation?
I think what you are trying to do is this. This assumes you add a new div "myError" that holds your error message. You'll also need to consider not submitting the form too if validation doesn't pass.
function calculatePrice() {
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var error = document.getElementById("myError");
if (GasPrice == "" || Distance == "" || Mileage == "") {
error.style.display = "block";
return false;
}
else {
error.style.display = "none";
return true;
}
}