I realize this might be a silly question, and I apologize in advance, but I was hoping there'd be an easier way to do this.
For example if I set the text of a div like so:
divOne.textContent = someVariable + "/5";
and I have about 60 divs that are like cells in one div container. Is there any way I can update the text values without manually calling it each time? The problem isn't when they change a cell one by one, it's when they hit the reset button. Is there a way to do it without writing 60 lines of text? Would the only solution be something like:
divOne.updateText = function() { this.textContent = someVariable + "/5"; }
and would that even be an ok solution? Creating 60 extra parameters each with a function overkill?
Any information on this subject is greatly appreciated, thanks in advance.
Edit:
The reason why I didn't use the for loop to begin with is because each cell has a different max value, aka the 5 from someVariable + "/5" . I was asking after your comment though if it'd be better to just do something like this instead though:
someDiv[0].max = 5
someDiv[i].textContent = someDiv[i].points + "/" + someDiv[i].max;
//the above would be inside a for loop.
over doing the .updateText = function
Based on your comment, you can just loop through your array using a for loop.
var someDiv = [];
// Fill array with elements
for (var i = 0, len = someDiv.length; i < len; i++) {
someDiv[i].textContent = someDiv[i].points + "/" + someDiv[i].max;
}
Related
Not sure if this is possible to even do so I'll give it a quick shot and see if anyone has any solutions, ahem.
Is there any way I could store these variables into an array, and change them through the array as such;
function themepreviewchange() {pretaskbartxt=curcolsch[0];pretaskbartxtprs=curcolsch[1];preactivetitle=curcolsch[2];preinactivetitle=curcolsch[3];pretbgradinactive1=curcolsch[4];
pretbgradinactive2=curcolsch[5];pretbgradactive1=curcolsch[6];pretbgradactive2=curcolsch[7];cpwhite=curcolsch[8];cplightg=curcolsch[9];cpsilver=curcolsch[10];cpmidgray=curcolsch[11];
cpgray=curcolsch[12];cpblack=curcolsch[13];cpblue=curcolsch[14];cpprussian=curcolsch[15];cpwincyan=curcolsch[16];cpyellow=curcolsch[17];cpfont=curcolsch[18];cphover=curcolsch[19];
cpatext=curcolsch[20];preinvert=curcolsch[21];shuffleflop=curcolsch[22];discheckinv=curcolsch[23];enacheckinv=curcolsch[24];invcheckinv=curcolsch[25];prespritesheet=github+curcolsch[26];
cwpp=curcolsch[27]}
var settings = pretaskbartxt,pretaskbartxtprs,preactivetitle,preinactivetitle,pretbgradinactive1,pretbgradinactive2,pretbgradactive1,pretbgradactive2,cpwhite,cplightg,cpsilver,cpmidgray,
cpgray,cpblack,cpblue,cpprussian,cpwincyan,cpyellow,cpfont,cphover,cpatext,preinvert,shuffleflop,discheckinv,enacheckinv,invcheckinv,prespritesheet,cwpp,currentcolour
And just do a for loop?
for(var i=0; i<curcolsch.length; i++){settings[i]=curcolsch[i]}
The current result just ends up changing the value of that number in the array, and just changes it to the same thing as the current position in the curcolsch array. So my question is; how would I go about using a quicker route than just spamming the same set of variables with one step up in the array like I addressed above?
Just to be clear I'm not completely insane with the variable count problem, the whole reason i'm asking is so I can get rid of them.
Hoping this isn't your homework assignment....
let settings = {
pretaskbartxt: curcolsch[0],
pretaskbartxtprs: curcolsch[1],
...
cwpp: curcolsch[27],
};
for (const aThing in settings) {
console.log(`value of ${aThing} is ${settings[aThing]}`);
}
Should give you the basic idea....
I was hoping for a quick straight forward answer without the need to rewrite half my code, so I've just ended up removing all my variables in a replacement for a single array so I can switch easier and it's more compact + better than any other solution.
var preactive = [undefined,undefined,'--preactivetitle','--preinactivetitle',undefined,undefined,
undefined,undefined,'--prewhite','--prelightg','--presilver','--premidgray','--preblack',
'--preblue','--preprussian',undefined,'--preyellow','--prefont','--prehover',undefined,
'--preinvert']
function themepreviewchange() { precolsch = undefined; precolsch = schemes[themecurrent]
for(var i = 0; i<preactive.length; i++){docelem.style.setProperty(preactive[i], precolsch[i])}
gradient = "linear-gradient(90deg, " + precolsch[4] + "," + precolsch[5] + ")";
Is there anyway to use jQuery to dynamically set the attributes of HTML elements that are stored in variables?
For example, at one point in my application, a user creates a varying number of select input fields. For eventual processing by PHP, the elements need to be named in the format name='input'+siteNumber+'['+x+']', where x is the number of elements created in a for loop.
Here's a rough sketch of what I'm thinking needs to be done - THIS IS NOT FUNCTIONAL CODE, IT IS ONLY AN ILLUSTRATION.
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
//HERE'S THE INPUT TO BE NAMED
selectInput = "<select></select>";
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
//THIS IS WHAT I'D LIKE TO ACCOMPLISH - SETTING THE ATTRIBUTE - THOUGH THIS UNDERSTANDABLY DOES NOT WORK IN THIS PARTICULAR FORMAT
this['inputArray' + siteNumber].push(selectInput.attr("name", "species"+siteNumber+"["+x+"]"));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Thank you.
Thanks everyone - I actually ended up deciding to handle this a little differently, but it works perfectly - rather than storing the elements in variables, I used a function instead...
function inputs(siteNumber, x){
return ("<select name='selectInput"+siteNumber+"["+x+"]'>"+list+"</select>");
};
$(".number_select").change(function(){
numberFound = $(this).val();
siteNumber = $(this).parent().attr('data-site_number');
this['inputArray' + siteNumber] = [];
for(x = 1; x <= numberFound; x++){
this['inputArray' + siteNumber].push(inputs(siteNumber, x));
};
$(this).parent().append(this['inputArray' + siteNumber]);
};
Don't know why I didn't think of this in the first place, it seems obvious to me now. Oh well, live and learn.
To vaguely answer your question, you can dynamically generate an element and use jQuery's attr for adjusting the name attribute pretty easily like so.
var select = $('<select>').attr('name', 'add-name-here');
$('<option>').attr('value', 'some-value').text('Option').appendTo(select);
$('#wrapper').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper"></div>
Which outputs
<select name="add-name-here">
<option value="some-value">Option</option>
</select>
In your case, instead of adding it to #wrapper you would build up the select box as you need and append it to whichever select box has the change? Not sure your specific use case. Hope it helps.
I have a series of arrays that contain words I want to use as text in various HTML divs (there are about 35 of these, I included only a few for brevity).
var bodyplan = ['Anguilliform', 'Compressiform', 'Depressiform', 'Filiform', 'Fusiform', 'Globiform', 'Sagittiform', 'Taeniform'];
var mouthposition = ["Inferior", "Jawless", "Subterminal", "Superior", "Terminal"];
var barbels = ['1', '2', '4 or more'];
var caudalshape = ['Continuous', 'Emarginate', 'Forked', 'Lunate', 'Rounded', 'Truncate'];
I have a switch function that is supposed to change the text based on user selections:
switch(n){
case 1:
changelabels(bodyplan, 8);
break;
case 2:
changelabels(mouthposition, 5);
break;
case 3:
changelabels(barbels, 3);
break;
case 4:
changelabels(caudalshape, 6);
break;
case 5:
changelabels(dorsalspines, 8);
break;
default:
alert("handquestsel error")}};
Finally, I have the function which I would like to make the changes (except it doesn't):
function changelabels(opt1,opt2){
var i = opt2;
var im = opt2 - 1;
var c = 1;
var index = 0;
while (i>=c){
var oldlbl = document.getElementById("rb" + c + "lbl");
var newlbla = opt1.slice(im,i);
var newlblb = opt1.toString();
oldlbl.innerHTML = newlblb;
c = c + 1
index = index + 1
}};
I know the code for my function is just plain wrong at this point, but I have altered it so many times that I'm not sure what's going on anymore. At one point I did have the function able to change the text, but it did so incorrectly (it parsed the name of the array, not extracted a value from the array as I wished). Please help. I know I am overlooking some fundamental concepts here, but am not sure which ones. I've lost count of the hours I've spent trying to figure this out. It's seems like it should be so simple, yet in all my chaotic attempts to make it work, I have yet to stumble on an answer.
EDIT: I want my switch statement to call the function and pass to the function, the appropriate array from which to pull the labels from. The purpose of the app is to help a user learn to identify fish. When the user makes selections on the page, a series of pictures will be shown for various character states with an accompanying label describing the state. For example, when the user selects Mouth Position a series of divs will show the different mouth positions that fish have and have a label below the picture to tell the user what that certain character state is called. I can get the pictures to change just fine, but I am having a hell of a time with the labels.
Why not just something along the lines of:
document.getElementById("bodyplan_label").innerHTML = bodyplan[bodyplan_index];
You seem trying to put everything in really abstract data structures, I see no reason to. Just keep it simple.
Also bodyplan has only 8 elements, so bodyplan[8] will give you an out of bounds exception because arrays start at 0 as is common in all modern programming languages.
If I'm reading your requirement and code correctly, in your switch statement you are passing both a reference to the appropriate array and that array's expected length - you don't need the second parameter because all JavaScript arrays have a .length property.
You don't want to use .slice() to get the individual values out of the array, because that returns a new array copied out of the original - just use arrayVariable[index] to get the individual item at index.
So, putting that together try something like this (with your existing array definitions):
switch(n){
case 1:
changelabels(bodyplan);
break;
case 2:
changelabels(mouthposition);
// etc.
}
function changelabels(data) {
var i,
lbl;
for (i = 0; i < data.length; i++) {
lbl = document.getElementById("rb" + (i+1) + "lbl");
lbl.innerHTML = data[i];
}
}
Notice how much simpler that is than your code? I'm assuming here the elements you are updating have an id in the format "rb1lbl", "rb2lbl", etc, with numbering starting at 1: I'm getting those ids using (i+1) because JavaScript array indexes start at zero. Note also that you don't even need the lbl variable: you could just say document.getElementById("rb" + (i+1) + "lbl").innerHTML = data[i] - however I've left it in so that we have something to expand on below...
Within your function you seem to be changing the labels on a set of elements (radio button labels?), one per value in the array, but you stop when you run out of array items which means any leftover elements will still hold the values from the previous selection (e.g., if the previous selection was "bodyplan" with 8 options and you change to "mouthposition" with only 5 - you probably should hide the 3 leftover elements that would otherwise continue to display the last few "bodyplan" items. One way to do that is instead of setting your loop up based on the array length you could loop over the elements, and if the current element has an index beyond the end of the array hide it, something like this:
function changelabels(data) {
var i,
lbl,
elementCount = 20; // or whatever your element count is
for (i = 0; i < elementCount; i++) {
lbl = document.getElementById("rb" + (i+1) + "lbl");
if (i < data.length) {
lbl.innerHTML = data[i];
lbl.style.display = "";
} else {
lbl.innerHTML = "";
lbl.style.display = "none";
}
}
}
If these elements are labels for radio buttons (just a guess based on the ids) then you'd also want to hide or show the corresponding radio buttons, but I hope you can figure out how to add a couple of lines to the above to do that.
(As mentioned above, be careful about having element ids count up from 1 when the array indexes start at 0.)
If the above doesn't work please post (at least some of) the relevant HTML - obviously I've just had to guess at what it might be like.
SOLUTION: Changed the scope of the array variables to local by moving them into the function where they are used, instead of having them as global variables at the top of the page. I don't understand as I was following every rule of variable declaration. But for some unknown reason, global variables in javascript are abhorrent.
Solution Edit: Found an error in declaring my global variables. This may have been the source of my problem of why I could not access them. But it is a non-issue at this point since I corrected my code.
I don't understand what your trying to achieve exactly with your code. But to pass a variable (in this case an array) by reference you just have to add "&" before the variable.
function the_name(&$var_by_ref, $var_by_value) {
// Here if you modify $var_by_ref this will change the variable passed to the function.
}
More: http://php.net/manual/en/language.references.pass.php
Hope that helps.
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!!
What I want to do is that: a webpage with continuously updating content. (In my case is updating every 2s) New content is appended to the old one instead of overwriting.
Here is the code I have:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.write(number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
var my_interval = setInterval('send_msg()', 2000);
However, in both IE and Firefox, only one line is printed out, and the page will not be updated anymore. Interestingly in Chrome, the lines are being printed out continuously, which is what I am looking for.
I know that document.write() is called when the page is loaded according to this link. So it's definitely not the way to update the webpage continuously. What will be the best way to achieve what I want to do?
Totally newbie in Javascript. Thank you.
Lily
I would have a div or some other container, like this:
<div id="msgDiv"></div>
Then write to it like using .innerHTML, like this:
var msg_list = new Array(
"<message>Hello, Clare</message>", "<message>Hello,Lily</message>",
"<message>Hello, Kevin</message>", "<message>Hello, Bill</message>"
);
var number = 0;
function send_msg()
{
document.getElementById("msgDiv").innerHTML += number + " " + msg_list[number%4]+'<br/>';
number++;
}
var my_interval = setInterval(send_msg, 2000);
You can see a working example of this here
You can append to the innerHTML property:
var number = 0;
function send_msg()
{
document.getElementById('console').innerHTML += (number + " " + msg_list[number%4]+'<br/>');
number = number + 1;
}
This code will append the message to an element with an id of console, such as
<div id="console"></div>
By the way, it is bad practice to call setInterval with a string.
Instead, pass the function itself, like this:
var my_interval = setInterval(send_msg, 2000);
I would start by looking at the jQuery library. This will save you a lot of pain.
What you want to do is keep inserted lines into a table, using eg:
$('table tbody').append('<tr><td>some value</td></tr>');
This would be an excellent opportunity for you to learn a little DOM programming.
Using the DOM to update the page should result in less overhead than simply concatenating more HTML into it. Find the node you want to put the updates into, and do an appendChild on each subsequent addition.
The answers to this question may be helpful: What's a simple way to web-ify my command-line daemon?