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
Related
Let me start by saying, that while I have some programming experiencing (some basic C from a college class and I once wrote a FORTRAN programm in college for a professor), I am utterly new to JS and beginning to get a bit frustrated.
For some reason, even after reading tutorials and watching several YouTube videos on objects, I seem unable to wrap my head around it. I understand the fundamentals and have no problems doing very basic stuff, like writing a loop that prints out increments on a HTML site, but every time I try something practical, I am completely at a loss.
Here is my current problem: I have created this HTML site that generates a shopping list. Basically, when I click on one of the buttons next to an item name, it adds that item to the list in the middle of my screen. Thanks to Google I found a piece of JavaScript code which, through try and error, I managed to tweak for this purpose:
<!-- click this button to add the item-->
<button onclick="myFunction('ITEM1', 100)" class="sidebarbuttons" >ITEM1 </button>
/* Create a List one line at a time- */
<script>
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
So far, so good. Now I want to get the net price for all the items. Which means, When I click the button, I want a function to add the price of that item to a variable and then display that variable in a field with
document.getElementById("result").innerHTML = total_sum;
Here's my question: how, oh my god, how do I do this? I thought I could add the following:
function myfunction(x,y){
var sum = 0;
var sum+=y;
}
document.getElementById("result").innerHTML = 'sum';
Obviously, this doesn't work at all. Can you please give me some hints what I have to do to make this work?
First of all,
please consider to study JavaScript better, because it's a falsy easy programming language and it's very dangerous to copy&paste without knowing the language. It's quite normal to read a lot, watch a lot and don't know where to start, and it's the main reason because people hates JavaScript: because we don't know well JavaScript. So consider to read the book series "You Don't Know" by Kyle Simpson.
About your question. You can add a variable to storage the sum of your items and when you click to an item, you can add to it:
var total_sum = 0;
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
showResults(y);
}
function showResults(price){
total_sum += parseFloat(price)
document.getElementById("result").innerHTML = total_sum;
}
JSBIN
Let me know ;)
So you are on the right track. Picking up where you left off in your last code block, there are few things you will need to change.
//declare the variable outside of the function... otherwise it will only be available to you within that function.
var totalSum = 0;
// then within your function you will be able to successfully add to the global totalSum variable
function calculateSum(x){
totalSum += x;
// and lastly... set the innerHTML within the function... which should equal the variable totalSum
document.getElementById("result").innerHTML = totalSum;
}
Hope this helps.
I have searched the posts to find a solution to what I would like to do. I want to create a list for <datalist> using a JavaScript array. I found a for loop that worked for someone else, and I modified it slightly to work with a 2D array. I have used the code below on JSFiddle, and it works, but when I include it into my larger code, the <datalist> does now show up even though the code is simply copied and pasted into my larger code.
Also, I'm not sure how to change the code below to jQuery, if you could help with that I would greatly appreciate it as well.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
];
var options = '';
for(var i = 0; i < test.length; i++) {
options += '<option value="'+test[i][0]+'" />';
document.getElementById('maltList').innerHTML = options;
}
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>
You can use the jQuery#append method to add a list of options (mapped from the data in your test array using Array#map) to your datalist. Since the code you had before was working as a snippet, though, I'm not sure whether this will actually help you in whatever context it had failed previously.
Let me know if you get any error messages and I will try to help you resolve them.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
]
$('#maltList').append(test.map(function (e) {
return new Option(e[0])
}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>
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
I'm working on a basic order form and I would like to see if I can build it from stratch.
I have a form which is made up of a table with 12 items listed and text input fields for item quantity. What I would like to do is have the code run through the form to check for any quantities that have been entered, then relate these values to the prices in an array.
So far I have the array:
var juicePrice = new Array();
juicePrice["citrusZing"]=20.00;
juicePrice["strawberrySmooth"]=22.00;
juicePrice["carrotSpin"]=21.50;
juicePrice["Tropical"]=20.75;
...
and a way to run through the form:
calculateTotal()
{
var juiceForm = document.forms["juiceform"];
//Get a reference to the juice the user Chooses name=selectedJuiceQty":
var selectedJuiceQty = juiceForm.elements["selectedJuiceQty"];
for(var i = 0; i < selectedJuiceQty.length; i++);
but I'm not quite sure how to connect the information from the form to calculate the totals. Can anyone point me in the right direction? Is it something like this?
for(var i = 0; i < selectedJuiceQty.length; i++){
var juiceTotal = 0;
if(selectedJuiceQty[i]>0) {
juiceTotal += juicePrice[selectedJuiceQty[i].value]*selectedJuiceQty;
//If we get a match then we break out of this loop
break;
}
return total;
}
Is it possible to use the same name tag for each field or should I just use citrusZingQty = parseInt(document.getElementById("citrusZing").value); for each item? Then I would have to list all of the items, which doesn't seem a very elegant way. What would happen if multiple items are selected?
Any help anyone can give to point me in the right direction would be great.
So you can do what you want. Michael pointed this out in the comments but it may have been overlooked.
var myPrices = new Object();
myPrices['eggs'] = 1.50;
myPrices['bread'] = 1.00;
// ...
Then you can loop through your form fields and check against your 'myPrices' object.
EDIT
To answer your question in the comments - I would not use the same name for all of my input fields. It does make looping through the form easier perhaps. However, using the id/class of the input tag is not a nice solution in my opinion. HTML id/class are there for CSS/Javascript manipulation and using it to identify which fruit the input represents will not be apparent to other developers working on the project (I realize this may be a small project for you but it's best not to start any bad habits). I would name each input after the juice/drink it represents.
I have been trying to find a way to replace a carriage return with the html break. I think it is cr13? Not entirely sure. I am new to programming. I have a content page. So i am setting the javascript in the content area. I have many other javascripts in the page. One hides and shows columns. So i have a way to find the columns. But i think i need to find the cells? It is only one column where this is needed. I am using asp.net, with vb.net, importing a sql server 2008 db. Unfortunatly this must be done in just javascript to avoid page reloads on the click of a button.
Thanks.
function showComments() {
Begincol_num = 8
Endcol_num = 9
Commentcol_num = 7
rows = document.getElementById("<%=GridView1.ClientID%>").rows;
for (i = 0; i < rows.length; i++) {
rows[i].cells[Begincol_num].style.display = "none";
rows[i].cells[Endcol_num].style.display = "none";
rows[i].cells[Commentcol_num].style.display = "";
}
}
The idea is put the js to replace the cr with br within this function(if possible). I am at a loss as to where to start to call the replace in the comment cells. There are 30 comment cells, in the comment column at the moment and will only grow as it goes. This function is called on the click of a button that is not meant to return to the server, which is what i meant by only js.
I am trying to be as clear as possible. I know vb and asp but js makes no sense to me.
Thank you for the help.
In javascript, new lines are represented by "\n", the new line character. If you want to replace a new line with a <br />, then use the string replace function
var stringWithBR = stringVarName.replace("\n", "<br />");
Assuming your comments are contained directly inside the cells with no other tags in between, you could do this:
// ...
for (i = 0; i < rows.length; i++) {
rows[i].cells[Begincol_num].style.display = "none";
rows[i].cells[Endcol_num].style.display = "none";
var commentCell = rows[i].cells[Commentcol_num];
commentCell.style.display = "";
commentCell.innerHTML = commentCell.innerHTML.replace("/\n/g", "<br />");
}
// ...
But it is not a clean solution to do such a thing on showing the comments at all. You should do it either directly on the server or else on load. Otherwise, if you show and hide the comments more than once, you will do some unnecessary work which may not be a performance- but definitely a design problem.
After all problems could occur if there are line breaks inside HTML tags inside a comment. You can prevent that by using innerText and textContent but that would erase any tags. Better solutions are complicated.