I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, when I run the Firebug I can see that all elements have been added correctly except for the Username which value is "". I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Few mistakes that you made:
Forgot to close the clientlist array
Forgot to actually push the newly added client
This code below should work correcting a few mistakes that you made along the way.
var clientlist = [{
"username": "John",
"fullname": "John Doe",
"email": "john.doe#hotmail.com",
"type": "client",
"password": "jdoe2"
}];
function NewClient() {
var found = false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
} else {
found = false;
}
}
if (found) {
$("#msj").html("User already exists!");
} else {
var newUser = {
fullname: $("#fullname").val(),
username: user,
email: $("#email").val(),
type: "client",
password: $("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
Made a fiddle for you:
http://codepen.io/gabrielgodoy/pen/xOxoWw?editors=1011
I guess, you have several issues.
Ending bracket of the clientList
For loop and the found variable
pushing new user to the client list.
I have corrected them and included it below.
<script>
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}]
function NewClient(){
var found=false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username==user) {
found = true;
break;
}
}
if (found){
$("#msj").html("User already exists!");
}
else{
var newUser={
fullname:$("#fullname").val(),
username:user,
email:$("#email").val(),
type:"client",
password:$("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
</script>
Related
I'm trying for 5 days. I couldn't come up with the solution.I'm a student.
function createUser(){
let user_name = document.getElementById("name").value;
let user_ph = document.getElementById("tel").value;
let user_dob = document.getElementById("date").value;
let new_passwd = document.getElementById("new-password").value;
let user_passwd = document.getElementById("confirm-password").value;
let user_data = new Array();
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph!=user_ph}))
{user_data.push({
"user_name": user_name,
"user_ph": user_ph,
"user_dob": user_dob,
"user_passwd": user_passwd
})
alert("account created for this mobile number");
localStorage.setItem("users",JSON.stringify(user_data));
window.location.href="./login.html";
}
else
{
alert("This number is already linked with another account");
window.location.href = "./reg.html";
}
}
I tried this code and it actually store the data in array even with the empty data and the page don't go to the other page. It stays there.
function login(){
let user_tel = document.getElementById("tel").value;
let user_passwd = document.getElementById("password").value;
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph==user_ph && v.user_passwd==user_passwd})){
alert("welcome!");
//window.location.href="../profiles/home.html";
}
else
{
alert("Phone number and password is not right")
window.location.href="./login.html"
}
}
this is code for my login page
I have tried to create a login function which when the user enters the vaild name and password then it will print "welcome user " else "invalid user".
In my code it accepts one username and password and showing invalid for another one...I cant understand why its showing like this...
code:
<script>
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name+inp[i].mail);
console.log(out[j].Name+out[j].mail);
if((inp[i].Name== out[j].Name)&&
(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome
user";
}
else{
document.getElementById("out1").innerText="Invalid
user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
</script>
find fiddle here:
https://jsfiddle.net/xp1Lrbdh/#&togetherjs=d0wTznLFgu
The issue is because of the iteration you are doing even after finding if entered user is valid user. In simple terms, putting a break statement solves your problem.
See the snippet below:
let userName=document.getElementById("input1");
let mailId=document.getElementById("input2");
var out=[{Name:"dhanam",mail:"dhanamram98#gmail.com"},
{Name:"alamelu",mail:"alamu98#gmail.com"}];
function input()
{
var input=userName.value;
var output=mailId.value;
var created=[{Name:input,mail:output}];
return created
}
function output()
{
var inp=input();
for(var i=0;i<inp.length;i++)
{
for(var j=0;j<out.length;j++)
{
console.log(inp[i].Name, inp[i].mail);
console.log(out[j].Name, out[j].mail);
if((inp[i].Name== out[j].Name)&&(inp[i].mail==out[j].mail))
{
document.getElementById("out1").innerText="welcome user";
break;
}
else{
document.getElementById("out1").innerText="Invalid user";
}
}
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
NOTE: This is not a best practice to verify credentials also avoid using var, use let, const instead
const accounts = [
{
name:"dhanam",
mail:"dhanamram98#gmail.com"
},
{
name:"alamelu",
mail:"alamu98#gmail.com"
}
]
function output() {
const nameNode = document.getElementById("input1")
const mailNode = document.getElementById("input2")
const name = nameNode.value
const mail = mailNode.value
const found = accounts.find(a => a.name === name && a.mail === mail)
if (found) {
document.getElementById("out1").innerText="welcome user";
} else {
document.getElementById("out1").innerText="Invalid user";
}
}
var but=document.getElementById("out");
but.addEventListener("click",output);
So I have this code that someone had posted from awhile back. It has been working flawlessly for a year now. It takes the google form answers and posts them to discord channel as a webhook. Now since yesterday, it is not working anymore. Nothing has changed with the script.
function onSubmit(e) {
var form = FormApp.getActiveForm();
var POST_URL = "****";
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var response = latestResponse.getItemResponses();
var items = [];
for (var i = 0; i < response.length; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
try {
var parts = answer.match(/[\s\S]{1,1024}/g) || [];
} catch (e) {
var parts = answer;
}
if (answer == "") {
continue;
}
for (var j = 0; j < parts.length; j++) {
if (j == 0) {
items.push({
"name": question,
"value": parts[j],
"inline": false
});
} else {
items.push({
"name": question.concat(" (cont.)"),
"value": parts[j],
"inline": false
});
}
}
}
var options = {
"method":"POST",
"payload": JSON.stringify({
"content":"Hello, World!",
"embeds":[{
"title":"War Times Form",
"fields":items,
"footer":{
"text":"***Please verify these are Correct***"
}
}]
})
};
Logger.log("[METHOD] onFormSubmit");
Logger.log(items);
Logger.log(options);
var response = UrlFetchApp.fetch(POST_URL, options);
Logger.log(response);
};
This is what logging is saying its submitting
[19-11-24 10:13:28:400 PST] {method=POST, payload={"content":"Hello, World!","embeds":[{"title":"War Times Form","fields":[{"name":"Post your clan name:","value":"fds","inline":false},{"name":"Post your name","value":"fds","inline":false},{"name":"Clan that you are declaring against:","value":"dfsa","inline":false},{"name":"Days and times your group is available was HQ fight (must be in EST):","value":"sdaf","inline":false}],"footer":{"text":"***Please verify these are Correct***"}}]}}
However, I keep getting this error:
Request failed for https://discordapp.com returned code 400. Truncated server response: {"message": "Cannot send an empty message", "code": 50006} (use muteHttpExceptions option to examine full response)
at onSubmit(Code:54)
Any help that anyone can give me would be great. I have tried contacting discord support and they wont help as its API/Dev
So found the answer had to add to the options that get sent through the request. Discord apparently changed it and didn't tell anyone that you have to declare it
"contentType" : "application/json",
I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Several problems with your for loop.
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
So what are we working with? clientlist is array so clientlist[i] is an element of that array...which happens to be an object.
user value is a string so there is no way to equate a string to object in the if.
Correction there would be to inspect the correct property value in object:
if (clientlist[i].username == user) {
Next problem is that the loop keeps going even if a match is found. As loop continues found will be updated for each iteration. Thus found will only be set based on the very last object in array regardless if a match was already determined.
To correct this could put that for loop in a function so it breaks the loop by returning true if match is found. Alternative would be use other array methods like Array.prototype.some() which returns a boolean based on conditional in callback. Or use break if a match is found to prevent loop continuing.
break will be simplest to plugin to the code so final would be
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;// quit loop since we found a match
}else{
found = false;
}
You need to change this
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
to
var found = false;
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;
}
}
You can use Array#some for this: It lets you run a callback against each entry in an array and determine if it matches a condition. some stops and returns true the first time you return a truthy value from the callback, or returns false if no calls to the callback return a truthy value.
So:
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
That's more concise with ES2015+ arrow functions:
if (clientlist.some(entry => entry.username === user)) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
Also note that you don't want to reuse the same Client object each time, because on the next add, you'll just change the existing object's properties. Instead, create a new object each time:
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}];
function NewClient() {
var user = $("#username").val();
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
$("#username, #fullname, #email, #password").val("");
$("#msj").html("New client has been created");
}
}
$("#btn").on("click", NewClient);
<div>
<label>
Username: <input type="text" id="username">
</label>
</div>
<div>
<label>
Fullname: <input type="text" id="fullname">
</label>
</div>
<div>
<label>
Email: <input type="text" id="email">
</label>
</div>
<div>
<label>
Password: <input type="password" id="password">
</label>
</div>
<div><input type="button" id="btn" value="Add"></div>
<div id="msj"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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.