I'm currently using the following JavaScript in a Google Chrome Extension to automate the 'add to cart' process for purchasing sneakers on nike.com;
var size_i_want = "11";
function fRun()
{enter code here
// Select size option.
var sizesList=document.getElementsByName("skuAndSize")[0];
for(var i=0; i<sizesList.length; i++)
{
if(sizesList.options[i].text.trim() == size_i_want)
{
sizesList.selectedIndex = i;
}
}
var aButtons = document.getElementsByTagName("button");
for(var i = 0; i < aButtons.length; ++i)
{
if(aButtons[i].className.indexOf("add-to-cart") > -1)
{
aButtons[i].click();
}
}
}
function fTick()
{
if(document.getElementsByName("skuAndSize")[0] != undefined)
{
setTimeout("fRun()", 600);
//fRun();
}else{
setTimeout("fTick()", 300);
}
}
setTimeout("fTick()", 300);
This script works perfectly for nike.com in the States, however does not work correctly for nike websites in other countries like the UK and Sweden.
As you can probably tell I am new to JavaScript and am still researching high and low to understand the language. However I understand this comes down to the fact that
var size_i_want = "11";
value is set as an integer (number) however on the Nike UK website the node that this affects contains letters, for example "UK 10.5".
Would somebody be able to help me declare a new variable and set it's value so that it contains both letters and numbers? I also have a feeling that this will impact the script as well, so help around that area is much appreciated too.
In javascript, variables are not typesafe, so you don't declare them as integers or strings. Coincidently:
var size_i_want = "11";
This is already a string. So you should already be able to add letters to it. Just change it to:
var size_i_want = "UK 10.5";
As millerbr already said javascript is not type safe.
The mix of letters and numbers should not have impact on the script, because
size_i_want = "11";
size_i_want = "UK 10.5";
are both strings.
Related
If I do:
var number = 3500;
alert(number.toLocaleString("hi-IN"));
I will get ३,५०० in Hindi.
But how can I convert it back to 3500.
I want something like:
var str='३,५००';
alert(str.toLocaleNumber("en-US"));
So, that it can give 3500.
Is it possible by javascript or jquery?
I think you are looking for something like:
https://github.com/jquery/globalize
Above link will take you to git project page. This is a js library contributed by Microsoft.
You should give it one try and try to use formt method of that plugin. If you want to study this plugin, here is the link for the same:
http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
I hope this is what you are looking for and will resolve your problem soon. If it doesn't work, let me know.
Recently I've been struggling with the same problem of converting stringified number formatted in any locale back to the number.
I've got inspired by the solution implemented in NG Prime InputNumber component. They use Intl.NumberFormat.prototype.format() (which I recommend) to format the value to locale string, and then create set of RegExp expressions based on simple samples so they can cut off particular expressions from formatted string.
This solution can be simplified with using Intl.Numberformat.prototype.formatToParts(). This method returns information about grouping/decimal/currency and all the other separators used to format your value in particular locale, so you can easily clear them out of previously formatted string. It seems to be the easiest solution, that will cover all cases, but you must know in what locale the value has been previously formatted.
Why Ng Prime didn't go this way? I think its because Intl.Numberformat.prototype.formatToParts() does not support IE11, or perhaps there is something else I didn't notice.
A complete code example using this solution can be found here.
Unfortunately you will have to tackle the localisation manually. Inspired by this answer , I created a function that will manually replace the Hindi numbers:
function parseHindi(str) {
return Number(str.replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2406;
}).replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2415;
}));
}
alert(parseHindi("३५००"));
Fiddle here: http://jsfiddle.net/yyxgxav4/
You can try this out
function ConvertDigits(input, source, target) {
var systems = {
arabic: 48, english: 48, tamil: 3046, kannada: 3302, telugu: 3174, hindi: 2406,
malayalam: 3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
},
output = [], offset = 0, zero = 0, nine = 0, char = 0;
source = source.toLowerCase();
target = target.toLowerCase();
if (!(source in systems && target in systems) || input == null || typeof input == "undefined" || typeof input == "object") {
return input;
}
input = input.toString();
offset = systems[target] - systems[source];
zero = systems[source];
nine = systems[source] + 9;
for (var i = 0 ; i < input.length; i++) {
var char = input.charCodeAt(i);
if (char >= zero && char <= nine) {
output.push(String.fromCharCode(char + offset));
} else {
output.push(input[i]);
}
}
return output.join("");
}
var res = ConvertDigits('१२३४५६७८९', 'hindi', 'english');
I got it from here
If you need a jquery thing then please try this link
Use the Globalize library.
Install it
npm install globalize cldr-data --save
then
var cldr = require("cldr-data");
var Globalize = require("globalize");
Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));
//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));
//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());
//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');
var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");
console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500)); //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००
https://github.com/codebling/globalize-example
A common scenario for this problem is to display a float number to the user and then want it back as a numerical value.
In that case, javascript has the number in the first place and looses it when formatting it for display. A simple workaround for the parsing is to store the real float value along with the formatted value:
var number = 3500;
div.innerHTML = number.toLocaleString("hi-IN");
div.dataset.value = number;
Then get it back by parsing the data attribute:
var number = parseFloat(div.dataset.value);
This is a Columbus's egg style answer. It works provided the problem is an egg.
var number = 3500;
var toLocaleString = number.toLocaleString("hi-IN")
var formatted = toLocaleString.replace(',','')
var converted = parseInt(formatted)
i am new to Google apps script, i want to create string of random characters in the code given below in variable body2.
function myfunction() {
var files = DriveApp.getFiles();
while (files.hasNext(`enter code here`)) {
Logger.log(files.next().getName());
}
var recipient = Session.getActiveUser().getEmail();
var subject = 'A list of files in your Google Drive';
var body1 = Logger.getLog();
var body2;
for(var i=0;i<6;i++)
{
body2[i]=BigNumber.tostring("Math.floor(Math.random()*11)");
}
body=body1+body2;
MailApp.sendEmail(recipient, subject, body);
};
but when i run this function, it says "TypeError: Cannot find function tostring in object 0. (line 12, file "Code") " i can't understand how to solve this error?
Why we have to multiply random by 11 , can it be multiplied with any integer number?
what if i want that string in only capital letters.!
Some other question
1) i don't have enough knowledge of JavaScript, is it good to learn GAS directly?
2) i can't find proper written material or documentation for GAS , the material available at Google's official site is seems to be updating time by time , what to do then ? any link to material would help me .!
I guess I just figured
function randomStr(m) {
var m = m || 15; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
Hope someone finds it helpful.
As for a random string use this its better:
Math.random().toString(36). 36 is the base thus will use letters and numbers in the string.
As for gas documentation, the official page is pretty complete. It changes because it constantly improves and adds new services.
I have this charIdGeneration() in my GAS library
function charIdGenerator()
{
var charId ="";
for (var i = 1; i < 10 ; i++)
{
charId += String.fromCharCode(97 + Math.random()*10);
}
//Logger.log(charId)
return charId;
}
Ive been working on this regex for days now and I cant get it figured out. It either passes everything I put in there or it kicks everything out and I cannot seem to make it function. Admittedly I am new to doing this complex of stuff with Javascript so It may be that you realy cant do this.
I want to check onkeypress what was entered into the input and then validate it to x, y, or z. Then from there send it on about its way to do other neat stuff.
So the question is what the heck am I not understanding about RegExp?
Here is a FIDDLE for it.
function val() {
var gradeIn = document.querySelectorAll("#letGrade input[type=text]");
var checkGrade = new RegExp(/[xyz]/gi);
for (var i = 0; i < gradeIn.length; i++) {
if (!checkGrade.test(gradeIn.value)) {
alert ("This must be X, Y, or Z");
return false;
} else {
return true;
}
}
};
EDIT/UPDATE:
I was trying to do this on keypress and validate each text input individualy however this was realy kinda squishy in the grand scheme of things and not working out exactly correct. I decided to validate all text inputs onsubmit and have everything go all at once. Updated code is below.
function calcGPA() {
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be A, B, C, D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
gVals.push(grades[i].value);
cVals.push(contacts[i].value);
}
//Other cool stuff happens here
};
Now to just finish the conversion piece for the letters to numbers and the math piece. Thank you for your help on this!
The problem's not only with your regular expression.
if (!checkGrade.test(gradeIn[i].value)) {
You weren't checking each grade. Now if you want it to only be those characters, you have to extend the regular expression a bit. Also, there's no point calling new RegExp if you're using native syntax.
var checkGrade = /^[xyz]+$/;
That means that you're OK with the fields being like "xxyyz" or "zzy". If it should just be one character, that'd be
var checkGrade = /^[xyz]$/;
For this question, it might be a little vague, because i just dont understand it at all, its probably the wording.. from what i learn in class it seems a lot harder. So im lost as to where to begin.. if someone can help walk me through it easier i would appreciate it!
Question: Design a Program that will read the same parts inventory file described in the problem 6. the parts are: (Record code, part number, part description, and inventory balance) validate the record code and part number on each record, and print the details of all valid records whose part numbers fall within the value AA3000 and AA3999 inclusive. Also print a count of these selected records at the end of the parts listing.
Now, i hope you can understand what its asking because i sure dont. Any help or a small walk through would be awesome. This is the code i am supposed to start out from that was given to me.
var Rec_Code = new Array(11,11,11,12,11,12,11,13,11,14);
var Numer = new Array(2000,3000,3003,3008,3999,2000,1090,3678,3777,3543);
var Alpha = new Array("AA","AA","AX","AA","AA","AA","AB","AA","AN","AA");
var Desc = new Array("X","L","S","F","R","U","T","N","Q","Y");
var Inv_Bal = new Array(12,13,14,23,34,56,32,45,67,77);
also, this was given to me, which is basically what i have to do, but dont know how to completely do it.
use the vars that I provided to create 5 parallel arrays, RecCode, AlphaPart of part number, Numeric part of the part number,Description and Inventory. You need to search the first 3 arrays for:
RecCode of 11
AlphaCode of 'AA':
Numeric Code betweewn 3000 - 3999 inclusive
when you find a match increment a count and display the Description and Inventory.
Assuming that all arrays are the same length and sorted appropriately, you can loop over one and display the information you need:
var count = 0;
for(var i = 0; i < Rec_Code.length; i++)
{
if(Rec_Code[i] == 11 && Alpha[i] == 'AA' && (Numer[i] >= 3000 && Numer[i] <= 3999))
{
console.log(Desc[i]);
console.log(Inv_Bal[i]);
count++;
}
}
var Rec_Code = new Array(11,11,11,12,11,12,11,13,11,14);
var Numer = new Array(2000,3000,3003,3008,3999,2000,1090,3678,3777,3543);
var Alpha = new Array("AA","AA","AX","AA","AA","AA","AB","AA","AN","AA");
var Desc = new Array("X","L","S","F","R","U","T","N","Q","Y");
var Inv_Bal = new Array(12,13,14,23,34,56,32,45,67,77);
var count = 0;
for(var i = 0; i < Rec_Code.length; i++)
{
if(Rec_Code[i] == 11 && Alpha[i] == 'AA' && (Numer[i] >= 3000 && Numer[i] <= 3999))
{
console.log(Desc[i]);
console.log(Inv_Bal[i]);
count++;
}
}
I am having a problem with a simple script that is supposed to update a page with some values(user input) that are turned from monthly to yearly (the numbers go into numeric fields created by confirmIT)
<script>
function update() {
for (var i = 0; i < 9; i++) {
var ans = parseInt(document.getElementById("bq10a_" + i).value, 10);
if (!isNaN(ans)) {
var new = ans * 12;
document.getElementById("bq10a_" + i + "calc").value = new;
}
}
}
return;
}
setInterval("update()", 1000);
</script>
this yields an Expected identifier error on line
var new = ans*12;
and i would appreciate any help on how to solve it
The word new is a reserved word in JavaScript and cannot be used as the name of a variable.
The error means that the parser expected an "identifier", which is to say that it expected to see a valid identifier.
Change the name of the variable and things should improve. In the code you've posted I think there's a { } nesting problem; there appears to be one too many before the return of the function.
edit — also as jbabey notes in a comment, your setInterval() call should be
setInterval(update, 1000);
It's not a good idea, generally, to pass strings to setInterval(), despite the advice of thousands of mouldy old instructional websites.
Word "new" -- is special in javascript language:
line is incorrect:
var new = ans*12;
try this:
var newvalue = ans*12;
More information on:
http://javascript.about.com/library/blreserved.htm
http://www.ecma-international.org/publications/standards/Ecma-262.htm