Looping through array and input value into field - javascript

I have a general question about a script to automate value inputs & clicking. The purpose is to select a site in the sites variable/concat into ns1 - ns2, click id add_gridVanity place the values into the input field and submit/close then repeat the process until the end of the array. I can't seem to get the for loop running. Sorry for the basic question.
sites = ["stonegrillla.com","schoolfoodbloomingroll.com","chapmanpizzeria.net","sushimasu.com","hmsbountyla.com","pailinthaicuisine.net","fullhouseseafood.com","cjssgourmetdelicatessen.com","bullsheadexpress.net","breakingbreadsf.net","lscaffe.net","latortagorda.org","pinecrestdiner.net","sunriserestaurant.net","tressf.net","hanazensf.com","piperade.org","mazzatsf.net","gaylordindia.net","thegrovefillmore.com","itstopscoffeeshop.net"]
for (i=0; i<sites.length; i++){
var base = 'ns1,ns2.';
var full = base.concat(sites[i]);
var sub1 = "ns1.".concat(sites[i]);
var sub2 = "ns2.".concat(sites[i]);
var both = sub1+'\n'+sub2;
$("#add_gridVanity").click();
$("#name").val(full);
$("#servers").val(both);
$("#sData").click();
$("#cData").click();
console.log(sites[i]); //test
};

Few basic stuff, you need to declare variables and add semicolons. Just declared sites and i and semicolon after sites. The tricky part about javascript is even with one small error with syntax or comma or semicolon etc, entire thing would fail and you wouldn't realize the same, since it might be very silly. Use dev tools in browser to check errors
var sites = ["stonegrillla.com","schoolfoodbloomingroll.com","chapmanpizzeria.net","sushimasu.com","hmsbountyla.com","pailinthaicuisine.net","fullhouseseafood.com","cjssgourmetdelicatessen.com","bullsheadexpress.net","breakingbreadsf.net","lscaffe.net","latortagorda.org","pinecrestdiner.net","sunriserestaurant.net","tressf.net","hanazensf.com","piperade.org","mazzatsf.net","gaylordindia.net","thegrovefillmore.com","itstopscoffeeshop.net"];
for (var i=0; i<sites.length; i++){
var base = 'ns1,ns2.';
var full = base.concat(sites[i]);
var sub1 = "ns1.".concat(sites[i]);
var sub2 = "ns2.".concat(sites[i]);
var both = sub1+'\n'+sub2;
$("#add_gridVanity").click();
$("#name").val(full);
$("#servers").val(both);
$("#sData").click();
$("#cData").click();
console.log(sites[i]); //test
}
Above answer is only for I can't seem to get the for loop running. Once you have the loop running i think you should be able to figure out the rest

Related

javascript if statement syntax (need help)

I've looked through the prior questions but do not see an answer that I can understand (they are all more complicated than mine).
I'm bootstrapping some javascript using old manuals and my experiences using a scripting language back 15 years ago.
By modifying a tutorial file I have this code and it works fine
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
total_current_draw.value = oemdc1 + oemdc2 + oemdc3
But I need to add this code so that if the user clicks a radio button (include_prism_draw) they get a different total.
if (oemdc4 == 1)
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
else
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
But I get the added value (prism_cd) in my calculation regardless of the radio button values (a "1" or a "0"). Even if neither button is clicked I still get the added value.
So I think I need some braces or parentheses or something.
I have the var prism_cd declared at the top of the doc and it is inserted into a results field so it is working in that sense.
Any help is much appreciated.
(Okay, found the edit link, they should make it more prominent).
I cut/pasted the code from #Adam and still get the prism_cd regardless of the state of the buttons. (prism_cd is a number I set as a var and it shows up accurately but even when I don't want it.)
the button code is below. Maybe there is a simple mistake
Include PRISM 1.5 mA current draw in calculation?
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="1" /> Yes
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="0" /> No
To answer the other question about the vars, they are from popups the user manipulates, the script adds the values from the popups and does so accurately until I add the yes/no code with the buttons.
If the user wants to add the prism current draw (prism_cd) they click yes and it is to be added but as I say it is getting added whenever the code is in the script. At this point I do not have either button set to be checked.
The rest of script works accurately as I can test with the spreadsheet I am porting it from.
I still have more things to work through but they are mostly based on this type of "if/else set a var" logic so once I get this working hopefully I should be good to go.
I very much appreciate the replies.
M./
I'm not certain what your problem is. But, the best practice for if..else syntax is to put both blocks in braces.
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
if (oemdc4 === 1){
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
} else {
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
}
Look at this question: Get Radio Button Value with Javascript
You cannot get the value of a number of associated radio-buttons by just doing
document.getElementById(ID).value;
also look at this question, why you should not give the same id to multiple HTML elements: Why is it a bad thing to have multiple HTML elements with the same id attribute?
Now a possible simple solution for you problem (according to solution from first link):
You could write a function, which returns the value of your two radio-buttons:
function getPrismDrawValue()
{
// predefined result, if no radio button is checked.
// in this case result will be 0 -> "No"
var result = 0;
// get a list of all HTML-elements with the name 'include_prism_draw'
var radios = document.getElementsByName('include_prism_draw');
// loop through all this elements and check if one of them is checked
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
// get the value of the checked radio button
result = parseInt(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
return result;
}
Now your variable oemdc4 should be declared like this:
var oemdc4 = getPrismDrawValue();
EDIT to answer new question:
now your problem is here:
var oemdc4 = parseInt(document.getElementById("prism_draw").value);
if you pass 1.5 to parseInt()-function it will return 1.
use function parseFloat() instead to get your expected result.
var oemdc4 = parseFloat(document.getElementById("prism_draw").value);

Run 4 individual form submit functions from a single button click using Javascript

I am currently attempting to make a page that would allow for users to search multiple knowledge bases from a single field.
Currently, I have been able to build this tool out so that clicking the corresponding button will search the designated tool, but I am trying to get a single button to search all 4.
Where I am stuck is the function tied to the All button. When I click it, it only appears to be running the last function in the group rather than opening 4 browser tabs with all 4 results.
I have attached a JSFiddle, in case my explanation is poor.
Note: The page is not pretty as I am trying to get it working before I add any CSS. I really just need JS advice. I am still somewhat of a novice with JS, so if anyone can provide a fairly simple solution, that would be most ideal.
Super Search Fiddle:
This is just to give an idea on how it might work depending on you needs. Ill assume that all the searches return a boolean value. So the code would go something like this:
function doAll() {
var msg = ["google","payroll","inquira","sdfc"]
var retvalue = [googleSearch(),payrollSearch(),inquiraSearch(),sfdcSearch()];
for (var i = 0; i < retvalue.length; i++){
if(retvalue[i] == false){
console.log(msg[i]+" search returned false");
}
}
}
It will do all the searches first and after it finishes, it will give out which searches failed, but you can change that functionality according to your needs.
Hope it helps
Update/Alternative(Almost same code):
function doAll() {
var msg = ["google","payroll","inquira","sdfc"]
var retvalue1 = googleSearch();
var retvalue2 = payrollSearch();
var retvalue3 = inquiraSearch();
var retvalue4 = sfdcSearch();
var retvalue = [retvalue1,retvalue2,retvalue3,retvalue4];
//var retvalue = [googleSearch(),payrollSearch(),inquiraSearch(),sfdcSearch()];
for (var i = 0; i < retvalue.length; i++){
if(retvalue[i] == false){
console.log(msg[i]+" search returned false");
}
}
}

Can't assign querySelectorAll() to a variable - weird behaviour

I was trying to crawl a very old website for a specific tag, I need to get it by it's for= attribute. So I used this piece of code.
var character = document.querySelectorAll("label[for=char_1]");
For some reason it returns an undefined, but I was using this script for a few days now and it worked like a charm. Here's the fun part. Typing that command in browsers console will result in undefined. But typing this alone:
document.querySelectorAll("label[for=char_1]");
Will return a proper NodeList. Why it won't assign to a variable...?
edit: It seems that deleting var and typing character without it will make it work. It's resolved but I would still love to get an answer to "why is this happening"?
edit2:
for (var i = 0; i < 15; i++) {
var character = document.querySelectorAll("label[for=char_" + i +"]");
console.log(character); // this will return [] from the script.
var color = character[0].children[0].style.color;
}
A simple for loop. All I get is Cannot read property 'children' of undefined. But I can type in the very same command document.querySelectorAll... and it will work in the browser and will return NodeList.
I had it working like this in a very hacky script. It worked.
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
edit3:
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
var character2 = document.querySelectorAll("label[for=char_2]");
var characterColor2 = character2[0].children[0].style.color;
// ...
The above code works without a single problem though. I don't think it's DOM not being ready as this code is also run from Greasemonkey script and it works. The only difference is the for loop.
var x = ""; // returns undefined, because it's a var assignment.
var elements = document.querySelectorAll('div');
That's expected behavior when pasted into the console.
edit: It seems that deleting var and typing character without it will make it work. It's resolved
I'm afraid you're creating a global scope variable now. or perhaps characters is an already defined variable in that scope.
Buhah, as I said in edit 3 "the only difference is the for loop". I was so busy trying to find an answer in the DOM-related things that I made the simplest mistake ever done in programming.
See?
char_1
With...
for(var i = 0...)
0! And I was testing char_1 in the browser instead of char_0. Which - truly - returns [] instead of something useful. Time to go on a holiday break I guess, my brain seems to be there already. :)

Can I make an array list adaptable in the HTML?

I am currently creating a spelling game where you drag and drop letters onto the corresponding words. At the moment I have a list of words in the array list that generate a grid dynamically.
The problem is when new words need to be added to the game, they have to be added through the HTML as that side of the office are not familiar with JavaScript/JQuery and not willing to learn.
What would be the best approach to this?
Is there a way that they can add things to the array in the script through HTML?
This is the script I have at the moment...
var listOfWords = new Array();
listOfWords['mat'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['cat'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['dog'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['pit'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['pot'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['fog'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['log'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['pan'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['can'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['man'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['pin'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['gag'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
Then i have script that takes the array list items and creates a grid dynamically.
var rndWord = null;
var guesses = new Array();
var shuffledWords = keys(listOfWords).slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 12);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < Object.keys(shuffledWords).length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
// IF FIREFOX USE cell.textContent = word[j]; INSTEAD
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
Thanks.
You could add a hidden object in the DOM:
<ul style="display:none;" id="wordlist">
<li data-word="mat" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav"></li>
<li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav"></li>
<!-- data-xxx can be read with JS, node["data-xxx"] or jQuery: node.data("xxx") -->
</ul>
You can then iterate over all elements using either jQuery or node.children:
var listOfWords = {};
var ul = document.getElementById("wordlist");
var i;
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = ul.children[i].getAttribute("data-audio");
}
console.log(listOfWords);
Demo
Hint: Please note that you're listOfWords is actually an object and not an array. An array supports only integer indexes and should be filled with .push.
Edit:
Please have a look at Tomas' answer. While this approach will definitely make it possible for your co-workers to add or change elements without actually writing JavaScript it's simply too much effort. Either way they will ask you questions how to add elements to the list. See also Dennis' comment.
Although Zeta's answer probably gives you an idea of how to do this, I'd say it doesn't really solve your actual problem. As you said yourself:
The problem is when new words need to be added to the game, they have to be added through the HTML as that side of the office are not familiar with JavaScript/JQuery and not willing to learn.
To me, this points to more fundamental difficulties in your team than just how to specify the dictionary in HTML; you seem to be working with people that are actively working against you. I see a couple of different ways to resolve this situation - some of them more provocative than others, while some requires more work on your part than others. You'll have to judge yourself which of them, if any, are applicable to you...
Force them to learn. It's not like they have to be jQuery masters to add a word to the dictionary - they just have to learn a specific syntax which you can teach them.
They are apparently capable of specifying the dictionary in HTML
markup, and can thus be assumed comfortable with some form of syntax.
I'd say your syntax for the dictionary is way simpler than what Zeta
suggested, so if they can learn one you should be able to teach them
the other.
If you need to, step up the company ladder and talk to their manager. They won't like it, but your development process probably will.
Do their work. Consider simplifying the whole process by reorganizing who does what in the development process. If the team responsible for the dictionary cannot add the actual key/value pairs to the code, maybe they can just ask you to do it for them? An email to a dedicated address, which you check a couple of times a day and add the corresponding stuff to the code would be one way to solve it.
Write them an admin system. This includes a lot of work on your part, both to create and support the feature - but it might earn you some goodwill in other matters. If the application should support later addition of new words, why not write a simple service that lets them add words to the dictionary from a web form? You store everything on the server, and load the dictionary with AJAX when you need it. The other team doesn't have to learn anything - they just enter the information in the form and click "send", and it's fixed.
My point is that if you're working with a team that doesn't want to meet half-way in a simple matter as this, you have bigger problems than just how to get these words into the list. I would focus on resolving the real problem here.
In short - No, you can't do it using only HTML
You need to write simple script which will generate js file containing array and you can include this file to your HTML file.
Basicly script may looks like this:
<?php
if (isset($_POST['code']) && isset($_POST['path'])){
$string = "listOfWords['" . $_POST['code'] . "'] = '" . $_POST['path'] . "';"
$fh = fopen('listofwords.js', 'a');
fwrite($fh, $string);
fclose($fh);
}
?>
<form action="" method="post">
<input type="text" name="code" />
<input type="text" name="path" />
<input type="submit" value="Add code" />
</form>
Of course this script is only for adding, if you need to edit/delete records you should rewrite script according your needs

Javascript variable

I'm struggling to get the result of one variable change another unrelated variable.
I have a script that is generating a random number between 0 and 19, which attaches itself to the global variable "index". I'd like to have another script that can read the result of the "index" variable and assign the appropriate text response from a different array, and post that text into a new variable (lets call it "response"). These two variables need to match up as well, the text ("response") following the associated number ("index"). e.g if the var index=0 then the var response= "good", when var index=1 then var response="bad" so on an so forth for all 20 possible outcomes put each array.
It seems pretty simple, but has eluded me accept for very complex and inefficient (i.e incompatible) means.
Thank you so much in advance, there's some very talented peeps out there!
Thanks for your prompt responses!
Here's some of the code.
var answers= new Array(20);
for (i = 0; i < answers.length; i++)
answers[i] = new Image();
answers[0].src = 'images/answer1.jpg';
//so on an so forth from 0 - 19
var index;
function askQuestion(){
index = Math.floor(Math.random() * (answers.length));}
So I've got the var index returning values which trigger the associated image, but then want to use the result of the index var to output an associated text too (using the another var). I can't believe I'm stumped on such a simple thing! I think I'm over complicating it with multiple variables or doubling the code again. Perhaps I'm just stuffing up the syntax. Damn, my javascript coding aint the greatest. Shouldn't of dropped out of maths all those years ago! Any ideas?
Do you just need this?
var response = yourDifferentArray[window.index];
The syntax window[varName] allows you to retrieve the value of a global variable from anywhere in your code.
So it was really simple. My problem was being too tricky (and a syntax error) by trying to use multiple scripts which weren't communicating. Here's the result.
var answers= new Array(20);
for (i = 0; i < answers.length; i++)
answers[i] = new Image();
answers[0].src = 'images/answer1.jpg';
//so on an so forth from 0 - 19
var index;
var remarks = ["remark0","remark1"] //..so on 0-19
var response;
function askQuestion(){
window.index = Math.floor(Math.random() * (answers.length));}
response = remarks[window.index];
Thank you so much for the help! GOLD STAR!!

Categories