I'm working on a score system that shows per question block, I'm using PHP to retrieve the data from a table and the javascript below to calculate the score. The problem is I want several score labels underneath each question block. So clearly I need an array to make this work, but currently I'm using this line to write the data onto document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
so this only applies to the first entry in the array. How do I make it loop through the entire array(score_label[]) and increase it's value so the code reads document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1);
this is the element javascript is writing to
echo "your total score: <span id='score_label[0]' name='score_board['".$score_board."']'></span>";
if there is need for I can post the entire function but I think it's mostly my lack of knowledge on arrays that's the issue here
If I'm reading your question correctly (current_score is the same for all elements???):
for (var i = 0; i < score_label.length; ++i)
document.getElementById("score_label[" + i + "]").innerHTML=""+current_score.toFixed(1);
I should mention that the id attribute of the form score_label[N] may be confusing.
Try to use foreach function to loop through the whole score_label array.
need to loop through a PHP array in JavaScript
Related
For my current project I fill an array by using the sql query
"SELECT names FROM students";
and throwing every response into an array named $names_array.
Then I use
foreach($names_array as $value) {
echo "<option>".$value."</option>";
}
to fill up a datalist with options so you can find a name using the list autocomplete or enter a name that is not yet found in the array.
Now here is the issue, if I click on an existent name I need to take a couple of other pieces of data from the table and fill in other input fields automatically.
So lets say the database table per student also has their age, birth, guardians number & guardians email.
How do I check if the typed in student already exists and if they do, get their additional data from the table?
If I can somehow get the entered name in PHP I could just look through the table which would be a lot faster but I've tried doing this and I can't seem to get it done.
I was using a very inefficient method where I json_encode an array gathered from the sql query
"SELECT * FROM students";
and then use
echo "<script>var names = ".$names_json."</script>";
to be able to fetch it in js. Now after parsing it and looping through it I can find my neccesary data but considering the database table already has 6000 options and is still increasing it's starting to take a while to loop through it, especially if the name I'm searching for is near the end of the array. Now this can take anywhere from 1 to 15 seconds where the website is completely frozen and it looks like it crashed until it's done and does what I need to do with the data.
I've tried using the solution offered here but that doesn't seem to change anything.
Please, does anyone know of a better way to do what I'm essentially already doing without temporarily freezing the website? Or maybe a completely different way of getting the other pieces of data? Thanks in advance.
for prevent the script loading to freeze the website load, you can add defer attribute, like so:
echo "<script defer>...some long logic....</script>";
For search easily through the array, you can sort it by the searched value, then use binary search
Also, you can store it in literal object, where the key is the name, and the value is object of all the student data. it will require some memory space, but make the search super fast
At first on server side - pagination/limit, do not "select all"
SELECT names FROM students WHERE names LIKE ? ORDER BY names LIMIT 20;
Second on client side - lazy loading via ajax, but first after, for example, user typed 3 chars of name.
I guess I should answer this question if anyone else ends up stumbling onto the same issue.
I change the foreach loop slightly by adding the ID as a data-id to the options
foreach($names_array as $value) {
echo "<option data-id='".$value['names_id']"'>".$value['names_name']."</option>";
}
Through js (and jquery) you can obtain the id of the chosen student like this:
currentVal = $("#inputID").val();
currentID = $("#listID option[value='" + currentVal + "']".attr('data-id');
now you can find the index of the chosen student in the namesArray doing this:
if (currentID != undefined || currentVal != "" || currentVal != " ") {
arrayIndex = namesArray.findIndex(x => x.names_id == currentID);
currentArray = namesArray[arrayIndex];
}
where namesArray is the var 'names' json parsed which I echo in the script seen in the question and the if block prevents it from even checking the array if the id is undefined or the input is empty.
I want to display some data i'm getting from the database and I'm displaying them in an html text field, as such:
for(var i= 0; i < array.length; i++) {
document.getElementById("f1").innerHTML += array[i]+ "<br>";
}
however, i'm getting repeated results as you might already know that arrays get data like "data_one" "data_one, data two" "data_one, data_two, data_three" (not sure if there is a term for that sort of behavior) and the problem is that the data gets repeated when being displayed as well. I can't get the data first completely and then display the array either because I can't use the Firebase data outside of it's loop.
I know in android you can clear the recycler view adapter, so I was wondering if there is some sort of similar thing in javascript.
You can do document.getElementById("f1").innerHTML = '' before your loop, to clean your view.
So I'm a bit new to coding and just needed direction, not necessarily doing it for me, but some steering.
I need to make a personality quiz that takes user choices and based on their choices gives them a certain outcome out of 4 choices at the end.
I know to create an array with questions and answers, but I'm not exactly clear what the next step is to set up a system to store user input.
Do I use another array to store the data?
Does that array have to refer to the buttons I make or the array earlier?
I'm not even sure if that's the right steps, I just need some clarification to the next step I should take after I create an array of my questions and answers.
Using another array should be fine, I would create the array for answers with empty strings right at the beginning. You already know the length of both the questions and answers arrays should be the same. So something along the lines of:
var answersArray = [];
for (var i = 0; i < questionsArray.length; i++) {
answersArray[i] = '';
}
After that you can use your buttons to fill the answersArray depending on the index that they belong. No matter the order in which the user answers the quiz, or if they don't fill all the answers. This way it will be easy for you to process the result in any way you need. All you need is an if statement that checks for the length:
if (answersArray[i].length > 0) {
// do something ...
}
Note that this is a very simple approach that does not take into account saving the data in any way (cookies, localstorage or database).
I'm newbie at JavaScript, and i'm having some issues using parse Json.
I have one array in PHP, and i'm passing the values from the PHP to JavaScript.
The problem is that i inserted the values inside a While loop, and When i get multiple values:
Value 1
Value 2
I receive this:
[{"id":"1","value":"1","month":"2"}, {"id":"1","value":"2","month":"2"}]
And to print the values i have to do that:
alert(obj[0].name);
alert(obj[1].name);
And i want to print the values together
How can i use a for loop in this situation? I just need a simple example to implement on my code, thanks.
I think you can get the length of the array using obj.length and then iterate over them and put all the values in a single variable. and then print/alert.
var len= obj.length;
var str="";
for(i=0;i<=len;i++)
{
str+=obj[i].name+' ';
}
something in the line, tied to your requirements.
Hope it helps.
I am using Greasemonkey/Tampermonkey to visit pages and make a change to a 100-element table based on what's on the current page.
Short term storage and array manipulation works fine, but I want to store the data permanently. I have tried GM_getValue/GM_setValue, GM_SuperValue, localStorage, and indexedDB, but I am clearly missing something fundamental.
Nothing seems to allow me to write the array into the permanent storage and then read it back into a variable where I can access each element, such that variablename[32] is actually the 32nd element in the table (Well, 33rd if you start counting at zero, which I do).
I need access to the entire 100-element table while the script is running, because I need to output some or all of it on the page itself. In the most basic case, I have a for loop which goes from 0 to 99, printing out the value of variablename[i] each time.
I have no predisposition to any method, I just want the frickin' thing to work in a Greasemonkey/Tampermonkey script.
Towards the top of the script I have this:
for (var i = 0; i <= 99; i++) {
currentData[i] = localStorage.getItem(currentData[i]);
}
The purpose of the above section is to read the 100 entries into the currentData array. That doesn't actually work for me now, probably because I'm not storing things properly in the first place.
In the middle, after modifying one of the elements, I want to replace it by doing this:
localStorage.setItem(
currentData[specificElementToChange], differentStuff);
The purpose of the above is to alter one of the 100 lines of data and store it permanently, so the next time the code at the top is read, it will pull out all 100 entries, with a single element changed by the above line.
That's the general principle.
I can't tell if what I'm doing isn't working because of some security issue with Firefox/Chrome or if what I want to do (permanently storing an array where each time I access a given page, one element changes) is impossible.
It's important that I access the array using the variable[element] format, but beyond that, any way I can store this data and retrieve it simply is fine with me.
I think you're going about this wrong. LocalStorage stores strings so the simplest way to store an array in LocalStorage is to stringify it into JSON and store the JSON. Then, when reading it back, you parse the JSON back into an array.
So, to read it in, you do this:
var currentData = JSON.parse(localStorage.getItem("currentData") || "[]");
To save your data, you do this:
localStorage.setItem("currentData", JSON.stringify(currentData));
Working demo: http://jsfiddle.net/jfriend00/6g5s6k1L/
When doing it this way, currentData is a variable that contains a normal array (after you've read in the data from LocalStorage). You can add items to it with .push(), read items with a numeric index such as:
var lastItem = currentData[currentData.length - 1];
Or, change an item in the array with:
currentData[0] = "newValue";
Of course, it's just a normal array, so you can use any array methods on it.