Passing a 2D array from one JavaScript function to another - javascript

I trying to collect information from the user based on a 2D array. I have problems passing on the 2D array from one function in Javascript to another function, as an array and not as text. What could I be doing wrong?
The array is this
Title Category1 Category2 Category3
Category1 Apples Blue Eyes
Category2 Oranges Green Legs
Category3 Pairs Yellow Arms
Mango Gray
The idea is to display Column1 first by having the "Title" as text and the Category list by buttons. On click of a button it should display the contents of the respected column. If, therefore, the user clicks on Category3, he should see Category3 as text and the options "Eyes", "Legs", "Arms" as buttons.
My problem is passing on the onclick the correct parameters as nextStep(this,database) is not working. When I pass on nextStep(this,\''+database+'\') of course it passes on the "database" as text and not as an array.
Any suggestions?
My HTML is a simple div.
<div id="mainPage"></div>
My Javascript starts on load...
window.addEventListener("load", starting, false);
function starting(){
var database = [[Title, Category1, Category2, Category3], [Category1,Apples,Blue,Eyes],[Category2,Oranges,Green,Legs],[Category3,Pairs,Yellow,Arms],[,Mango,Gray,]];
renderCategories(database,1);
}
function renderCategories(database, pos){
mainPage = document.getElementById("mainPage");
var catTitles = database[0];
var catTitle = catTitles[pos];
var allmainPage = database[2];
mainPage.innerHTML = '<div class="input-field col s12 m12"><h3>'+catTitle+'</h3></div>';
for(var i=0; i<allmainPage.length; i++){
var categoryListValue = allmainPage[i][pos];
if (categoryListValue !=""){
mainPage.innerHTML += '<div class="row"><button onclick="nextStep(this,database)" value="'+categoryListValue+'">'+categoryListValue+'</button></div>';
}
}
}
function nextStep(selection, database){
var selectedCat = selection.value;
alert(selectedCat);
var catTitles = database[0];
alert(catTitles);
}
window.addEventListener("load", starting, false);

I suggest you pass the database using the JSON.stringify() function, and then you can convert it back using the JSON.parse(), like this:
for(var i=0; i<allmainPage.length; i++){
let categoryListValue = allmainPage[i][pos],
databaseString = JSON.stringify(database);
if (categoryListValue !="")
mainPage.innerHTML += '<div class="row"><button onclick="nextStep(this,' + databaseString + ')" value="'+categoryListValue+'">'+categoryListValue+'</button></div>';
}
And then:
function nextStep(databaseString) {
let database = JSON.parse(databaseString)
}
Although I don't think this is the best way of doing it, it should fix your problem.
If you want my opinion, I think you should store the database in your localstorage and acess it using 'keys' as parameters (like database01) and such.

Related

Build hyperlink using value in array in javascript

I'd like to display hyperlinks in my page template based on values in an array.
If the page contains a certain value, I'd like to insert the corresponding hyperlink.
From another question, I've managed to cobble together a script that displays a link when a value is found in a string:
<style>
#viewSchoolLink
{display: none;}
</style>
<div id="schoolName">University of Houston</div>
<div id="viewSchoolLink">View on Some Link</div>
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("University of Houston") >= 0) {
// if so set display to block.
document.getElementById("viewSchoolLink").style.display = "block";
}
</script>
The thing is, I have like 80-90 schools in my list. I suppose I could create 80-90 separate divs with their own unique links, but I imagine there is a much more efficient way to do it. I have an array I've set up as follows:
const schoolLink = {
"University of Houston": "https://www.somelink.com/widget=4379",
"Vanderbilt University" : "https://www.somelink.com/widget=2537",
"University of Dundee": "https://www.somelink.com/widget=2845",
}
Is there a way I can loop through the array to find a match in the key and then insert the value from the array as a hyperlink?
<script type="text/javascript">
var div = document.getElementById("schoolName");
var text = div.innerHTML;
if (text.indexOf("key in array") >= 0) {
// if so display div and use value from the array as hyperlink
}
</script>
Or, since the only part of the link URL that is unique is the widget number, could I set up my array like this:
const schoolLink = {
"University of Houston": 4379,
"Vanderbilt University" : 2537,
"University of Dundee": 2845,
}
and then just build the URL based on the value in the array:
var part = value in array
var link = ''View on Some Link ';
to insert any of the HTML using Javascript we assign in the following manner:
var div = document.getElementById("schoolName")
div.innerHTML = "<a href='https://www.somelink.com/widget=value in array'/>"
if you want to enter the dynamic data in the place of "value in array", then:
div.innerHTML = `<a href="https://www.somelink.com/widget=${variable}"/>`

Need to pass an HTML ID for an image into a variable in javascript to use in various functions

I am trying to use code from html into javascript using code from https://www.geeksforgeeks.org/how-to-get-the-id-of-the-clicked-button-using-javascript-jquery/.
I am creating a memory game I have the images stored in an array and am able to click on it and it flips. I want to take the ID of 2 images and compare them but I need to pass the clicked ID variable from html into a javascript variable to store them for processing:
Here is my code for the detectClick function
**function detectClick(clicked) {
htmlID = clicked;
return htmlID;}**
Here is my HTML sample of my table of the first 4 array elements:
***<tr class ="success" >
<td onClick="changeimage('tblArr0',tblArr[0]);"><img src='memImages/CardBack.png' id="tblArr0"
onClick="document.getElementById('tblArr0').src='tblArr[0];detectClick(this.id);';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr1',tblArr[1]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr1"
onClick="document.getElementById('tblArr1').src='tblArr[1]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr2',tblArr[2]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr2"
onClick="document.getElementById('tblArr2').src='tblArr[2]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
<td onClick="changeimage('tblArr3',tblArr[3]);detectClick(this.id);"><img src='memImages/CardBack.png' id="tblArr3"
onClick="document.getElementById('tblArr3').src='tblArr[3]';"draggable="true" ondragstart="dragstart_handler(event)"></td>
</tr>***
I need to pass the detectClick(this.id) into the variable htmlID.
Any other ways of doing this or suggestions would help.
I have the the tblArr[] which contains another array called imgArr which stores the source name of the files for the images. I am able to have my array shuffled, now I need to be able to process the array objects to compare them. I just need to know how to get the ID from the image back into a javascript variable.
Thanks for suggestions and help in Advance!!
This should create your <td>s for as many as are available in the array:
function detectClick(clicked) {
htmlID = clicked;
return htmlID;
}
function loadSuccess() {
let container = document.getElementById("success");
for (let i = 0; i < tblArr.length; i++) {
let new_td = document.createElement("td");
new_td.setAttribute("onClick", "changeimage('tblArr" + i + "',tblArr[" + i + "]);");
container.appendChild(new_td);
let new_img = document.createElement("img");
new_img.src = "memImages/CardBack.png";
new_img.id = "tblArr" + i;
new_img.setAttribute("onClick", "this.src='tblArr[" + i + "];detectClick(this.id);';");
new_img.setAttribute("draggable", "true");
new_img.setAttribute("ondragstart", "dragstart_handler(event)");
new_el.appendChild(new_img);
}
}
<tr class ="success" id="success" onload="loadSuccess()"></tr>

How to Create Dynamic Object HTML and Assign Attribute Based Data Given

I have dynamic object (button and textbox) create by jquery where each time I press Add Transport. I took this code from this forum and modify little bit to suit my situtions (thanks to whom create this code).
Let me detail first regarding my dynamic items:
My set of group data are Trip[], Bus No[] and Amount[] .
This set can be multiple but consistent with 3 items only each group.
trip[] = button object
busno[] = text object
amount = text object
Below are my HTML script:
<div class="purchase-items-fieldset" style="clear:both;">
<div class="purchase-items-wrapper">
<div class="purchase-items">
<ul>
<li>
<input type="button" name="trip[]" value="PB" class="field btn-field">
</li>
<li>
<input type="text" name="busno[]" class="field txt-field">
</li>
<li>
<input type="text" name="amount[]" class="field txt-field">
</li>
</ul>
<input type="button" class="remove-line btn-remove" style="border:solid">
</div>
</div>
<button type="button" id="btnAddTrans" class="add-field" style="display: none">Add field</button>
</div>
Let says I have 2 set group data like below***(mydata="PB,WBX001,1000,P,WBK001,500")***
Then, my plan is:-
Group 1
trip[]=PB
busno[]=WBX001
amount[]=1000
Group 2
trip[]=P
busno[]=WBK001
amount[]=500
where I want Jquery/Javascript create 2 group dynamic object and assign value each object base on plan above :-
function assigndatatrip (mydata) {
//mydata="PB,WBX001,1000,P,WBK001,500"
//each 3 item are 1 set group data etc: PB,WBX001,500
//do split function and count how many set group
// create dynamic object
// assign data for dynamic object
//loop
//else no more data to assign then exit-return
}
I no idea where to start because I not so good on javascript/jquery function.
I hope anybody who face this problem can share and help me how to solve this problem. Thanks on advance who's reading and reply this question.
Thanks you.
If you will have that structure for your data : "each three items a group".
Then you can apply this logic:
$(document).ready(function() {
//Initialize vars
var start,
mydata = ["PB", "WBX001", "1000", "P", "WBK001", "500"]
//Loop to create items based on the array amount/3
for (start = 0; start < (mydata.length / 3); start++) {
//Target the elements of the array you need for each group
var trip = start * 3,
busno = trip + 1,
amount = trip + 2;
//Create the element to append
var item = "<div class='item'><ul><li>"
+ mydata[trip] + "</li><li>"
+ mydata[busno] + "</li><li>"
+ mydata[amount] + "</li></ul></div>";
//Append the group element
$('body').append(item);
}
})
.item {
color: white;
background: purple;
margin: 20px auto;
padding: 25px;
}
.item li {
list-style: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I must thanks to DaniP who have spirit and kindness, helping without asking. Thanks again.
I think and think many time regarding problem above, I can't use DaniP entire solution because I already have function AddTrans, SaveTrans and many more. My critical part only how to display back all a data I already save. Since object are dynamic my head getting sick to think and honestly I really bad on javascript/jquery coding.
Ok. If anybody using Dynamic Object inside Div and already run perfectly but do not know how to display back a data while create dynamic object then please consider my code below are one of solution on your reference.
function assigndatatrans(mydata) {
//var mydata = "PB,WBX001,500,P,WBK001,300"
var gdata = mydata.split(',').length / 3;
for (start = 0; start < gdata - 1; start++) {
$('#btnremove').click();
clickaddtrans();
}
var substr = mydata.split(',');
$.each($('.field'), function (index,value) {
$(this).val(substr[index]);
});
}
Let me explain my code for myself (I still on learning process JQuery function):-
First thing first is data string get from database
//var mydata = "PB,WBX001,500,P,WBK001,300"
then I need to count how many group data I have, each 3 item are 1 group then I need do small calculation
var gdata = mydata.split(',').length / 3;
After that, I know I already have function AddTrans and RemoveTrans then I need to clear first my dynamic object and show it again based how many group should be appear:-
for (start = 0; start < gdata - 1; start++) {
$('#btnremove').click();
clickaddtrans();
}
Finally, I learn some function $.each and Index and Value on JQuery recently and I try apply to make sure my data string can be perfectly insert into each field on my dynamic object. I think this part are really tricky for me and I try many time to make it working.
var substr = mydata.split(',');
$.each($('.field'), function (index,value) {
$(this).val(substr[index]);
});
That's all.... Now I can get my output run smoothly and workable. I can't say perfect! because I believe yours all who read this question can do better than this and far far more superior.
Anyway thanks so much and sleep well. :)

Can you perform certain onload functions from a link on a previous page

I'm not even sure what I'm thinking of will work and can't seem to find the right wording to get and search results that are remotely helpful so here goes.
What I want to be able to do is have a link from one page then cause the linked page to display a certain way. The code below is the script being used on the page I'll be linking to.
$(document).ready(function() {
$('.hideshow').click(function () {
var name = $(this).attr('id').replace("-L","");
if ($(this).hasClass("hidden")) {
$(this).addClass("shown");
$(this).removeClass("hidden");
$('div#' + name).show(500);
} else {
$(this).addClass("hidden");
$(this).removeClass("shown");
$('div#' + name).hide(500);
}
});
});
This code will hide or show content when links on the page are clicked using the id names used in the body of the file. Now what I want to be able to do is have the link from the previous page indicate certain links on this page as being shown. The following is some of the in body code.
<a class="hideshow hidden" id="cat-articles-L" style="cursor:pointer;"><font style="font-size:24px; color:#06F; text-decoration:underline;"> Cat Articles</font></a><br />
<div id="cat-articles" style="display:none;">
<a class="hideshow hidden" id="cat-beds-L" style="cursor:pointer;"><font style="font-size:18px; color:#06F; text-decoration:underline;">Cat Beds</font></a><br />
On default the "Cat Articles" are visible but "Cat Beds" is hidden until "Cat Articles" is clicked, then there could be sublevels so more items under "Cat Beds" The idea is when you link from the other page having it load with certain items already open.
Hope I made this clear enough, still new to this site and posting questions.
Add a parameter to the link on the original page. Something like domain.com/page.html?id=5 and then have javascript check for a QueryString of id and do something like a switch with it.
See How can I get query string values in JavaScript? for how to get QueryStrings if you aren't familiar.
If you need to pass multiple of the same type (example, multiple IDs), you can make an array and pass that array to the other page. In that array, include every id you want to display.
See an example of an array to url here: JavaScript Array to URLencoded
Example (Original Page):
var idArray = new Array(1,5,15,38);
var url = "http://www.blah.com/link.html?"+idArray.join('&');
Example (Linked page):
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
var idArray = qs["id"];
for (var i = 0; i < idArray.length; i++) {
switch(idArray[i]){
case 1:
//show link1
break;
case 2:
//show link3
break;
default:
//do nothing, but required
break;
}
}
Note: It may look that I'm using JQuery, but I'm not. This will work without it just fine.

Stop a page from refreshing after firing a function

I've been tasked with building a very simple app that that has a series of dropdowns in rows of 2, when 2 are selected, a simple functions concatenates the 2 values and gives an output next to them like so:
dropdown1 dropdown2 Output
What I'm trying to get is, once the second dropdown value is chosen the function runs and displays the output where it says output. But currently, what seems to happens is the output is displayed in a new window.
Here's what I have so far (HTML):
<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>
<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>
</form>
JavaScript:
function tryThis() {
var string, string1 = '';
var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;
var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}
Am I making this more difficult than it needs to be?!
That's because document.write clears the page before displaying something. You should never need to use that function.
Instead, you could append it to e.g. the body:
document.body.appendChild(
document.createTextNode(string + '_' + string2)
);
Have you noticed that your JS function is called tryThis() and on the event handler you're calling tryThsis()
However in your case I'd refrain from using document.write, good alternatives are appending to the body or having a DIV and changing the innerHTML of that DIV
First put an id on your form so that it is easier to access.
var a = (function () {
var myForm = document.getElementById("myForm"),
magic = function () {
var a = myForm.getElementsByTagName("select"),
b,
c = [];
for (b = a.length - 1; b > -1; b -= 1) {
c.push(a[b].value);
}
alert(c.join(" ") + " output");
};
myForm.onclick = magic;
}());
You were not specific as to what the extra "output" is supposed to be or how you want the data returned, but here you go. Instead of using an alert you could push the result into the value of a different form element. Do not use document.write as this cannot be deferred. If you attempt to defer a document.write operation it will replace the entirety of the body contents of the current page.

Categories

Resources