jquery put comma between every variable except last - javascript

I have a script that will insert the checked checboxes and radios in the value() of an input tag.
var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
$('#burger-navn').val(burgernavn);
Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them.
Thats the first thing.
Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in.
I hope this is accomplishable.

Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.
var checkedValues = document.getElementsByClassName('checkbox');
Iterate over this array, check for last values. (Check my comments in below code snippet)
var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
//append comma with each value
commaValues += checkedValues[i].concat(",");
}
//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
otherValues = checkedValues[0];
}
//finally concat both strings and put this concated string in input
$('#burger-navn').val(otherValues.concat(commaValues));
So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers

You can do this pretty easy with jQuery $.map.
var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");

Related

Making a custom function in Google Sheets, the code works outside of sheets but not in sheets

So I'm writing a custom function for Google sheets which is supposed to take a single row or cells, produce a 1 dimensional array and use that data to create a URL. This is basically so I can help my friends track the prices of an item in a video game.
I have ran the code in a javascript environment outside of Google Sheets and everything acted as expected. But when I put the code in the script editor, it runs with unexpected behavior. The range of cells will always be 1 row by 13 columns but some of the columns may be void so the script is supposed to truncate the array of values so that there are no empty indexes. Then it is supposed to insert a "." between each value as it is concatenated into a string to produce the final URL. For some reason it does not remove any values and the "." are ","s when the URL is created in the cell.
Here is the code:
function STONKLINK(prices, premrkt) {
var webLink = "https://turnipprophet.io?prices=";
var priceLink = "";
for (i = (prices.length - 1); prices[i] == 0; i--){
prices.pop();
}
for (i = 0; i < prices.length; i++) {
priceLink = (priceLink + prices[i] + ".")
}
priceLink = priceLink.substring(0, priceLink.length - 1);
if (premrkt == "N/A") {
webLink = webLink + priceLink;
} else if (premrkt == "Fluctuating") {
webLink = webLink + priceLink + "&pattern=0";
} else if (premrkt == "Small Spike") {
webLink = webLink + priceLink + "&pattern=3";
} else if (premrkt == "Large Spike") {
webLink = webLink + priceLink + "&pattern=1";
} else if (premrkt == "Decreasing") {
webLink = webLink + priceLink + "&pattern=2";
}
return webLink;
}
Any help is very much appreciated. Thank you so much.
EDIT: While I still do not understand why this is happening, and I would like to understand, I have added a simple work around. By adding this line of code
webLink = webLink.replace(/,/g, ".");
before the return, all the commas will be replaced with dots. Still, any insight into the problem will be much appreciated. Thank you again.
When you store values in Spreadsheets, the values which have a , are considered to be strings whilst the ones which have a . will be considered to be numbers.
So for example, if you have these values stored in the B column:
If you log the typeof(val1) and typeof(val2) (where val1 and val2 are the values stored in B1 respectively B2), this is what you will get:
So the issue you were encountering is due to this fact. The values you have stored in your sheet are numbers and when you try to build the webLink string they are converted into strings - therefore, the . for a number becomes ,.
Reference
Date and Number Formats

How can I get a true random from an array? Or should I do something else entirely?

I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!

Compare two array and find match in Javascript

for(var i = 0; i < textList.length; i++){
for(var j = 0; j < titles.length; j++){
if(textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
this is my code, but it won't return a match. I tried == and ===. But when i tested .includes() it worked. Can someone explain what's happening ?
If you are sure that all elements are in type String, you can use the method .search():
Prototype search
It will return the position of the match, if it dosent match in any position you will get -1 as return, soo > 0 it match.
I just tested your code with a very basic test example as follows:
let textList = ['book1', 'book2','book3']
let titles = ['book', ' tester', 'not_this', 'book2']
for(var i=0; i<textList.length;i++){
for(var j=0; j<titles.length;j++){
if (textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
And I got the expected result it includes my book2 the match is book2 counter 1 so with this specific code I would suggest looking at you input arrays.
With regards to your question regarding why .includes() works and this doesn't, again we would need to se your input arrays but I would hazard a guess that it is something to do with the type checking within this function.
Finally, as others have suggested, there are other (more succinct) ways of achieving this with built in array functions, however your original question was about why this code in particular doesn't work so I've left these out.

How to fix this string into array using .split() method?

I'm having trouble with JS .split() method in a GAS script. I copy and paste the headers of other google sheet as variable headers (the usual way will be copy and paste). This pasted selection contains some empty and undefined elements. I need to turn this elements in an array. So I split it and use the .filterto clean empty elements. But, when I run the script, the var arrayHeaders remains equal to headers, as if the .split(" ") didn't make any change, this way:
This is my code:
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
If I delete all spaces after paste the string and press space again, then the .split(" ") works well.
Before asking this question, I read this other one, but I'm still stucked with what is going wrong here.
Thanks in advance for any help!
I'm pretty sure your headers variable is not a String. Try this:
var arrayHeaders = headers.toString().split(/[\s\t]+/);
When you are performing split(""), make sure the words in the string are seperated by samething which are passing to .split() method.
Your arrayHeaders is same as the headers.
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
Here i think, the seperation of header is not same. make sure the seperation of headers are of one space or two spaces or three spaces..

javascript : how can i get array in different ways?

hi i have a little problem with my javascript
can i make the simple way to execute content of array with different character of word?
for example :
var word = new Array();
word [0] = "is";
word [1] = "am";
.
.
.
.
word [100] = "when";
var word should be access with 3 ways,in order to reduce process to execute arrays..
first : " "+ word +" ";
second : " "+ word;
third : word +" ";
-thank you for helping-
I'm not exactly sure what you are chasing (fill me in and I'll update), but I'd like to point out a far better way of filling in that array literal...
var word = [
'is',
'am'
];
You can see the index is calculated automatically, and you are not required to repeat the var name for each member definition.
Update
Maybe you want something you can call and get the next array member each time. This should do it...
function getNextMember(array, startIndex) {
startIndex = startIndex || 0;
return function() {
startIndex++;
return array[startIndex];
};
};
var getNextWord = getNextMember(word);
alert(getNextWord() + ' ' + getNextWord());
See it on jsFiddle.
And of course, if you are feeling naughty, you could add that function to Array's prototype.

Categories

Resources