value of property in nested object JS - javascript

claimReservation function. It should:
If the reservation exists and is unclaimed, welcome the user (use
alert).
If the reservation exists and is already claimed, inform the user
about the situation (use alert).
If there is no reservation, tell the user there is nothing under
their name (user alert).
Use 'Bob' and 'Ted' to test your code.
my code :
var reservations = {
'Bob': { claimed: false },
'Ted': { claimed: true }
}
var name = prompt('Please enter the name for your reservation');
var claimReservation = function (name) {
if(reservations.claimed == "false"){
alert("Welcome")
}
else if(reservations.name.claimed == "true"){
alert("You have a problem bruh!")
}
else{
alert("No reservation by that name bruh")
}
}
claimReservation("Leeann");
claimReservation("Bob");
claimReservation("Ted")
`

Looks like you're trying to use a prompt to get the name and then reference "name" as the passed in variable to the function? Please see the updated code and let me know if you have any questions.
var reservations_ = {
'Bob': {
'claimed': false
},
'Ted': {
'claimed': true
}
};
var claimReservation = function(name) {
if (reservations_.hasOwnProperty(name) === false) {
alert("No reservation by that name bruh");
return;
}
if (reservations_[name].claimed === false) {
alert("Welcome " + name);
} else if (reservations_[name].claimed === true) {
alert(name + ", you have a problem bruh!");
}
};
claimReservation("Leeann");
claimReservation("Bob");
claimReservation("Ted");
var name = prompt('Please enter the name for your reservation');
claimReservation(name);

Related

Print one message for specific condition, different message for everything else

My homepage prompts you to enter your name upon entry, but I want it to print a special message when i enter my nickname. Instead, it prints the same message every time.
window.onload = function namePrompt() {
let person = prompt("Please enter your name", "");
if (person != null) {
document.getElementById("name").innerHTML =
"welcome, " + person + ", to the pyrogaming/covid2009 homepage!";
}
else if (person = pyro || Pyro || PYRO) {
document.getElementById("name").innerHTML =
"hey, me! hope you've been making substantial changes!";
}
}
person = pyro || Pyro || PYRO is not valid JS
There are three errors. = is assignment, not comparison and you would need quotes and test each one with ===
person === "pyro" || person ==="Pyro" || person === "PYRO"
Instead use toLowerCase and a ternary. In any case stay DRY (Don't Repeat Yourself)
I also recommend eventListener instead of onload
window.addEventListener("DOMContentLoaded", () => {
const person = prompt("Please enter your name", "");
if (!person) return; // empty string or null
const text = person.toLowerCase() === "pyro" ?
"hey, me! hope you've been making substantial changes!" :
`welcome, ${person}, to the pyrogaming/covid2009 homepage!`;
document.getElementById("name").innerHTML = text;
})
<span id="name"></span>
You need to first check the name if it's yours and after that display the default message
When comparing, use ===, not = - this one is "assign value", not comparing
Use string values instead of just PYRO
I'd also suggest to use toLowerCase method, so you don't need to worry about input case. "Pyro", "PYRO", "pyro" - they all will be the same for comparison
window.onload = function namePrompt() {
let person = prompt("Please enter your name", "");
if (person != null) {
if(person.toLowerCase() === 'pyro') {
document.getElementById("name").innerHTML =
"hey, me! hope you've been making substantial changes!";
} else {
document.getElementById("name").innerHTML =
"welcome, " + person + ", to the pyrogaming/covid2009 homepage!";
}
}
}
<div id="name"></div>
window.onload = function namePrompt() {
let person = prompt("Please enter your name", "");
var msg
if (person != null) {
if (person.toLowerCase() == "pyro") {
msg =
"hey, me! hope you've been making substantial changes!";
} else {
msg = "welcome, " + person + ", to the pyrogaming/covid2009 homepage!";
}
document.getElementById("name").innerHTML = msg
}
}
<div id="name"></div>

Why is javascript array object undefined after logging array contents to the console?

Trying to access and compare the value of an object's property inside my LobbyQueue class. I've successfully added data to the array from server.js, and logged it. but when I try to use a method from LobbyQueue class to access & compare an object's property value form the array, I get undefined for the array index.
I've tried looping through the array's contents from inside the Queue class. this is where I'm getting undefined's
LobbyQueue.js:
class LobbyQueue {
constructor() {
this.players = [];
}
enqueue(player) {
this.players.push(player);
}
dequeue() {
if (this.isEmpty()) {
return "Wait List is Empty";
}
return this.players.shift();
}
hasUser(username) {
if (this.players.length == 0) {
return false;
} else {
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i][username] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i][username] === username) {
console.log("username comparison entered...");
}
}
}
}
}
}
module.exports = LobbyQueue;
server.js:
const queue = new LobbyQueue();
var gameRooms = [];
io.on("connection", socket => {
console.log("a user connected..." + "\n");
socket.on("addPlayer", username => {
if (queue.hasUser(username)) {
console.log("user already in queue...");
} else {
console.log("New user joined: " + username);
queue.enqueue({
username: username,
id: socket.id
});
socket.join("lobby");
const players = queue.getAll();
console.log("Players in queue: " + "\n" + JSON.stringify(players));
io.sockets.in("lobby").emit("players", players);
}
});
...
I expect hasUser()to prevent a duplicate connection being created. but its not returning true when the username already exists in the queue. it's as if the user doesn't exist when it loops over the array. but since the queue was logged to the console and the username and connection id are there, Im not sure whats going on.
You need change condition to
typeof this.players[i]['username'] === "undefined"
Because you need access property name 'username'
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i]['username'] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i]['username'] === username) {
console.log("username comparison entered...");
}
}
}
hasPlayer(username) {
return this.players.find(player => player['username'] == username) != null;
}

Check for duplicate name before adding in the dropdown

I have two issues:
I want user to add the values in the dropdown but before that I am checking if the value is already present in that using this function:
function IsNameAlreadyPresent(List,Name){
$.each($("'#'+List option"),function(i,e){
if(e.innerHTML == Name){
return true;
}
});
}
function AddOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent(List,Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
AddNewOption(Name);
}
}
I want to use this same function many times in my code to check whether the value entered is unique or not by passing the id of the dropdown and the name to be entered. but somehow this doesnt work.
how to pass the id as a parameter ($("'#'+List option")?
I am using the same function to edit the text of the option as well. but somehow if the user clicks edit and he doesnt want to change the text and clicks OK it gives an alert that the option is already present.
The option is only once including the one open in the popup. how to check this ?
var x = document.getElementById("List");
var l_sName = x.options[x.selectedIndex].text;
$("#List option[value="+l_sName+"]").remove();
Your selector is wrong, it should be $("#"+List+" option"). Also return inside $.each() will not return from your function, but break $.each() if false. Change your IsNameAlreadyPresent(List,Name) to this:
function IsNameAlreadyPresent(List, Name) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name) {
result = true;
return false;
}
});
return result;
}
For this part you can add a name to be excluded for checking, for example:
function IsNameAlreadyPresent(List, Name, Excluded) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name && e.innerHTML != Excluded) {
result = true;
return false;
}
});
return result;
}
function AddOptionName(Excluded = "") {
var Name = $("#txtName").val();
if (IsNameAlreadyPresent(List, Name, Excluded)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
} else {
AddNewOption(Name);
}
}
and then call it with AddOptionName( $("#"+List+" option:selected").html() );

JavaScript form validation improvement

I have a user profile form with 15 text fields and some dropdown and an textarea. the scene is that user can input field in profile form. On save it is no necessary to fill all fields, whatever the user fills in fields i have to validate and save in database via ajax call.
for now i am using validation like this,
var first_name = document.getElementById('id_candidate_profile-first_name').value;
....
var status = false;
if(first_name != ''){
status = regex_test(first_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-first_name').innerHTML = "first name should only have alphabets";
}
else{
status = true;
}
}
if(middle_name != "" & status = true){
status = regex_test(middle_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-middle_name').innerHTML = "middle name should only have alphabets";
}
else{
status = true;
}
}
if (last_name != '' & status = true){
status = regex_test(last_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-last_name').innerHTML ="last name should only have alphabets";
}
else{
status = true;
}
}
if (date_of_birth != '' & status = true){
status = regex_test(date_of_birth, ck_date);
if(status==false){
document.getElementById('candidate_profile_error-date_of_birth').innerHTML ="date of birth should be in YYYY-MM-DD format";
}
else{
status = true;
}
}
if (birth_place != '' & status = true){
status = regex_test(birth_place, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-birth_place').innerHTML ="birth_place should only have alphabets";
}
else{
status = true;
}
}
if (nic != '' & status = true){
status = regex_test(nic, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-nic').innerHTML ="nic should be in this format 12345-1234567-1";
}
else{
status = true;
}
}
if (status = true) {
// made ajax call
}
function regex_test(variable, regex){
var _result = false;
if(!regex.test(variable)){
_result = false;
}
else {
_result = true;
}
return _result;
}
Can be seen that there are lots of nested if else involved that irritate me, need some better way to do this? any best alternative?
You could create an array of validation objects, each object containing properties reg_ex, field, error_msg_container_id and error_msg:
var validationRules = [
{ reg_ex: first_name,
field: ck_name,
error_msg_container_id: candidate_profile_error-first_name,
error_msg: "first name should only have alphabets" },
{ reg_ex: date_of_birth,
field: ck_date,
error_msg_container_id: candidate_profile_error-date_of_birth,
error_msg: "date of birth should be in YYYY-MM-DD format" }
];
In the validation function, you just iterate through the whole array. That also makes it easier to maintain further input fields which you might add later.
P.S.: If you don't know how to iterate over an array, let me know.
Edit: Since requested by OP, an iteration function would look similar to this:
function isFormDataValid() {
for (i=0; i< validationRules.length; i++) {
// do the validation inside here, it will be repeated once for each validation rule;
}
return status;
}
In case you need variable property names from the array to read/write, use this syntax
Object[variable]
where variable contains the string that is the name of the property you need to access.
var myObject = {
name: "peter",
age: 46
};
var validationRules = [ { fieldname: 'name'}, { fieldname: 'age' } ];
for (var i=0; i< validationRules.length; i++) {
alert(myObject[validationRules[i].fieldname]);
}
You can use any form validation library. I personally recommend Parsley.
There's a simple validation form example: http://parsleyjs.org/doc/examples/simple.html

'undefined' appearing in alert

I am using Javascript to validate some code, and it works fine, but whenever I call alert to show the errors, at the beginning of the alert message I get 'undefined'. So when I should expect the alert to show 'Please enter a Low Target', instead I get 'undefinedPlease enter a Low Target'. Can somebody tell me what is wrong with my code?
//validation
var lowTarget;
var highTarget;
var errorList;
var isValid = true;
lowTarget = $('input[name="txtLowTarget"]').val();
highTarget = $('input[name="txtHighTarget"]').val();
if (lowTarget == "") {
errorList += "Please enter a Low Target\n";
isValid = false;
}
else {
if (isNumeric(lowTarget) == false) {
errorList += "Low Target must be numeric\n";
isValid = false;
}
}
if (highTarget == "") {
errorList += "Please enter a High Target\n";
isValid = false;
}
else {
if (isNumeric(highTarget) == false) {
errorList += "High Target must be numeric\n";
isValid = false;
}
}
if (isValid == true) {
if (!(parseFloat(highTarget) > parseFloat(lowTarget))) {
errorList += "High Target must be higher than Low Target\n";
isValid = false;
}
}
if (isValid == false) {
alert(errorList);
}
Assign some default value to errorList, e.g. empty string
var errorList = "";
Until you do that, initial value of errorList is undefined.
I was finding the same problem in my project while using
var try2 = document.getElementsByName("y_email").value;
alert(try2);
Now I used the following and it works well
var try2 = document.getElementsByName("y_email")[0].value;
alert(try2);
(So Be doubly sure that what you are using in correct format to use.)

Categories

Resources