This question already has answers here:
How can I make my search form work with uppercase and lowercase
(3 answers)
Closed 7 months ago.
This post was edited and submitted for review 7 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I'm using a script to search a CSV and return results for a small website. I can't for the life of me figure out how to make "LOREM IPSUM", "lorem ipsum", and "LoReM IPSsum" all return the same results.
The "City Type" functions as expected and is the only column that allows me to search by mixed case and return results. I expect this based on the "toLowerCase()" in that section of the script. However, when I try to make the other search items look the same, the entire search function breaks.
Can you help me with being able to search mixed case?
Script:
d3.csv("SubCityData.csv").then (function (data) {
var movies = data;
var button = d3.select("#button");
var form = d3.select("#form");
button.on("click", runEnter);
form.on("submit", runEnter);
function runEnter(e) {
d3.select("tbody").html("")
e.preventDefault();
e.stopPropagation()
var inputValue = d3.select("#user-input").property("value");
var filteredMovies =
movies.filter(movies => {
return (
movies['Coords'].includes(inputValue) ||
movies['City Type'].toLowerCase() === (inputValue).toLowerCase() ||
movies['Culture'].includes(inputValue) ||
movies['Alliance'].includes(inputValue) ||
movies['Owner'].includes(inputValue)
)
});
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js">
for (var i = 0; i < filteredMovies.length; i++) {
let output = filteredMovies
d3.select("tbody").insert("tr").html(
"<td>" + (output[i]['Coords'])+"</a>"+"</td>" +
"<td>" + (output[i]['City Type'])+"</td>" +
"<td>" + (output[i]['Culture'])+"</td>" +
"<td>" + (output[i]['Alliance'])+"</td>" +
"<td>" + (output[i]['Owner'])+"</td>" ) }
}
});
Currently, "City Type" functions how I need. So I changed all to the following, but when I do the same for "Owner" it breaks the search function:
var filteredMovies =
movies.filter(movies => {
return (
movies['Coords'].includes(inputValue) ||
movies['City Type'].toLowerCase() === (inputValue).toLowerCase() ||
movies['Culture'].toLowerCase() === (inputValue).toLowerCase() ||
movies['Alliance'].toLowerCase() === (inputValue).toLowerCase() ||
movies['Owner'].includes(inputValue)
)
});
When I use this line, it also breaks the search function:
var inputValue = d3.select("#user-input").property("value").toLowerCase();
If someone could help with the "Owner" line, I think I would be good to go.
Thanks!
You don't need to check for all cases if type sensitivity isn't important so you can make all the strings lowercase:
var inputValue = d3.select("#user-input").property("value").toLowerCase();
I have a function, which formats phone numbers, that is exported like so :
export function formatPhoneNumber(phoneNumber) {
var replace = ('' + phoneNumber).replace(/\D/g, '');
var format = replace.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!format) ? null : "(" + format[1] + ") " + format[2] + "-" + format[3];
}
and I am importing it into another file like so:
import {formatPhoneNumber} from '../ui/format_phone_number';
All is well and working, with the import. I wanted to mention that just in case there was some related issue.
I am looping over an object and want to format a phone number using the imported function. The odd thing is that when I try to format the value from the object, it returns null, but if I manually enter an int, or string it handles it correctly.
Here is my code:
$.each(signVendor, function( fieldId, value) {
if(fieldId == 'phone') {
console.log(value); // 262321345
console.log(formatPhoneNumber(8885551234)); // (888) 555-1234
console.log(formatPhoneNumber('8885551234')); // (888) 555-1234
console.log(formatPhoneNumber(value)); // null
value = formatPhoneNumber(value);
}
$formSignVendor.find('input[name=' + fieldId + ']').val(value);
});
Here are the console results in the same order as above:
I'm working on a CLI program, based on nodejs and the npm package "prompt".
Let say I want to have this prompt, putting the input in a variable pet:
Choose a pet:
(1) - Cat
(2) - Dog
(3) - Fish
(4) - Rabbit
(5) - Rat
: >
Basically I did the functionality, but I'm having the following problems:
If I use the conform function for custom validation - then my custom message - the multiline text - never appears. The name of the variable - pet - only appears. But I want to have validation, cause I want to make sure the user won't enter 333 for example.
If I remove the conform custom validation - I can have multiline text, but then something else happens: the blinking rectangle, where the entering happens, overlaps with the multiline text. And I can't make it blink after the last line of the multiline message.
(In the above example the blinking happens over the digit 5.)
Any idea how to resolve the two issues I have ? ... :)
================== EDIT: Added code samples ===================
This is how I generate the multiline text:
// generate the multiline text ..
var petsMessage = 'Choose a pet: \n';
var pets = [...];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += ' (' + (i+1) + ') - ' + pets[i] + "\n";
}
This is how I generate the prompt with multiline text, but no validation:
// define the prompt stuff ..
var promptInfo = {
properties: {
Pet: {
message: petsMessage,
required: true
},
}
};
And this is with validation, but multiline message not working:
// define the prompt stuff ..
var promptInfo = [
{
name: 'Pet',
message: petsMessage,
required: true,
conform: function(value) {
value = parseInt(value);
if(value > 0 && value < pets.length) {
return true;
} else {
return false;
}
}
}
];
I believe the problem was that in the second snippet with the validation you assign the actual question in the message property, you should assign it in the description. The message property refers to error message. Try this please:
var petsMessage = 'Choose a pet: \n';
var pets = ["dog","cat","frog"];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += '\t (' + (i+1) + ') - ' + pets[i] + "\n";
}
var prompt = require('prompt');
var promptInfo = [
{
name: 'Pet',
description: petsMessage,
required: true,
message: 'Options allowed:: 1'+'-'+pets.length,
conform: function(value) {
value = parseInt(value);
return value > 0 && value <= pets.length
}
}
];
prompt.start();
prompt.get(promptInfo, function (err, result) {
console.log('you Choose',result,'::::',pets[result.Pet-1])
});
Actually, the solution from "alex-rokabills" is not perfect too :( ... It's definitely better, but I still see issues.
If I use small amount of items then it's OK:
But if the number grows a little bit:
And for big prompts:
Also - can I get rid of the "prompt:" at the begining ? ...
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be many ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
Not only did you confuse yourself, but you crashed the browser! :-)
(The for loop never terminates because you push a new value to the list on every iteration.)
I could tell you what's wrong with the code in more detail, but you'll learn a lot more if you chase it down yourself. So what you need now is to learn the art of debugging.
Add a debugger statement at the beginning of your test() function:
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
debugger;
var info = prompt("hi " + input + " what is your name?");
for(i=0; i< list.length; i++){
if( info === list.length[i]){
console.log(list[i]);
}
else{
list.push(info);
}
console.log(list);
}
}
Now run test() and it will stop in the debugger at that statement. Look at the different panels in the debugger - you can view your variables and other stuff. Find the place where it has controls to let you step through your code. Single-step through the code and look at the variables as you go. You will soon discover what the problems are. In most browsers there are also keyboard shortcuts to let you step through the code more easily.
If you use Chrome, here is an introduction to the Chrome DevTools. There are similar tutorials for the other browsers too.
heres an algorithm :
Use an object to store the user no. and the count. like :
{"222":"3","444":"1"}
this means 222 has visited 3 times and 444 visited once. now every time a user checks in:
see if the key with the user's number exists, if yes increment the count. if no, add a new entry with count = 1.
check if the number is 5, if yes get free coffee and reset count to zero. skip if no.
I would solve the problem by storing the visit count in a dictionary that maps each customer's ID to the number of times they have visited. The dictionary is initially empty. When you look up an ID in the dictionary for the first time, you'll get undefined, which tells you that you must initialize the value.
The following demonstration has a couple of buttons that you can use to make Alice or Bob visit the shop. Click on the blue button at the bottom to start the demo.
function message(s) { // Simple output for a code snippet.
document.getElementById('display').innerHTML += s + '<br />';
}
var coffeeCount = {}; // Stores the number of visits by each customer.
function customerVisit(id) { // Called when a customer visits.
if (coffeeCount[id] === undefined) { // Check for first visit.
coffeeCount[id] = 0; // Initialize the visit count.
}
var count = ++coffeeCount[id]; // Increment the visit count.
message(id+': '+count+' visit'+(count == 1 ? '' : 's'));
if (count % 5 == 0) { // Check for free coffee.
message('→ Free coffee for customer '+id+'!');
}
}
<button onclick="customerVisit('Alice')">Alice</button>
<button onclick="customerVisit('Bob')">Bob</button>
<div id="display"></div>
Try including utilization of input elements; set visits count as value of property id, info at object list; call test with value of input element : id ; or at prompt : info . At five visits , display coffee , reset value of id to 0.
var list = {
"111": 0,
"222": 0,
"333": 0,
"444": 0,
"555": 0,
"666": 0
};
var test = function test(id) {
coffee.innerHTML = "";
var info;
if (id.length > 0 && !/^(\s)/.test(id)) {
if (list.hasOwnProperty(id)) {
++list[id];
} else {
list[id] = 1;
}
info = confirm("hi " + id + " this is your " + list[id] + " visit");
} else {
info = prompt("hi, please enter an id");
if (!!info && !/^(\s)/.test(info) && list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
} else {
info = prompt("hi, please input a different id");
if (!!info && !/^(\s)/.test(info) && !list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
}
};
alert("please try a different id")
};
for (var id in list) {
if (list[id] === 5) {
alert("hi " + id + ", thanks for visting " + list[id] + " times");
coffee.innerText = "☕";
list[id] = 0;
break;
}
};
console.log(list);
};
var inputs = document.querySelectorAll("input");
var coffee = document.getElementById("coffee");
coffee.style.fontSize = "5em";
inputs[1].onclick = function(e) {
test(inputs[0].value)
};
<input type="text" placeholder="please enter id" value="" />
<input type="button" value="click" />
<div id="coffee"></div>
n is number of costumer
Initially array is [0,0,0,.....n times]
All values are 0 because no costumer has visited the shop.
For n=5 array would look like
var a=[0,0,0,0,0];
1)To solve this problem in array.
2)Suppose we have array of size n.
3)then index of the array will be 0...n-1
4)So we can map id of costumer to the index.
5)And value will keep count of the number of visit for the index.
6)a[5]=11; here 5 is index and 11 is value
7)For our problem if customer with id i we increment a[i]=a[i]+1 if he visits .
8) Then we can check
if(a[i]+1 === 5) {
console.log("Custumer "+ i + " get a free coffee");
a[i]=0;
}
else {
a[i]=a[i]+1;
}
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be manyt ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
I will give you a short function to check how many times a specific value is at the array:
function countHowManyTimesAValueIsOnArray(arr, valueToCheck){
return arr.filter(function(arrayValueToCompare){
return arrayValueToCompare === valueToCheck;
}).length
}
Attention for the use of '===' instead of '=='. This will compare the value considering its type. 222 will not be found as "222"
No need to complicate things here's an simple way, just add a count function that search how many times user has enter
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
var info = prompt("hi " + input + " what is your name?");
var check=0;
for(i=0; i< list.length; i++){
if( info === list[i]){
check=1;
break;
}
}
list.push(info);
if(check==1){
count(info);
}
}
function count(info){
var count=0;
for(i=0; i< list.length; i++){
if(list[i]===info)
count++;
}
console.log(count);
}
}
This question already has answers here:
Access Javascript variables dynamically
(4 answers)
Closed 8 years ago.
I know there are a lot of questions about if it is possible to use variable variables in jQuery.
One of the questions is this one: click here.
I tried to use the answer, but I don't know how I can use it in my case.
var numberofquestions = 10;
var dataString = "";
for ( var i=1; i<=numberofquestions; i++ ) {
/* ------ first part ------- */
if (i==1) {
dataString = dataString + "q1=" + question1 + "&";
} /* ------ end first part ------- */
else if (i == numberofquestions) {
questionValue = "question" + numberofquestions;
qValue = "q" + numberofquestions;
dataString = dataString + qValue + "=" + questionValue;
console.log(dataString);
} else {
questionValue = question + i;
dataString = dataString + "q" + i + "=" + questionValue + "&";
}
}
The loop will run 10 times, and each time it needs to add a part to the already existing dataString.
What it needs to do is make this string:
q1=(value of var question1)&q2=(value of var question2) and so forth.
The vars question1, question2, ... question10 all hold a number.
The first part works, it outputs q1=5 in the console log, however, after comes a random string. The output string (the total string) looks like:
q1=5&q2=NaN&q3=NaN&q4=NaN&q5=NaN&q6=NaN&q7=NaN&q8=NaN&q9=NaN&q10=question10
Does anybody know what I'm doing wrong?
You should use an array for this. There is no such thing as "variable variables" in JavaScript.
You can access a variable through a string containing the variables name by using this[variableName], but again, you shouldn't. You should use an array for this.
In your case, you would use questionValue = this["question" + i], but one more time: Don't do it. Use an array instead.
I'm not sure why you're using "question" + numberofquestions which will be 10 every time