was hoping if anyone could help. I would like to be able to have it that whenever the arrays I pass into the function change it will display these values in a paragraph tag.
At the moment it doesn't rewrite it and I want it to display like it's steps (i.e 1. ... 2. ...) but it doesn't update the step number or take a new line either. This function is called in another function.
The code so far is:
//javascript code
//cred & grade are arrays
function breakdown(cred, grade){
var change = document.getElementById('bdown'); //'bdown' is the id of the <p>
var to;
var a = 1;
var x = 0;
for(var b = 0; b<cred.length; b++){
//alert(a)
to += a + ". (" + cred[b] + " x " + grade[b] + ")" + "<br /"; //show the step number and the values then take a new line
a++; //increment the step number
change.innerHTML=bdown.innerHTML.replace(change.textContent,to ); //wish to change <p>
}
}
//html code
// the paragraph wish to change
<div id="how"; style="color:white;display: none">
<p id="bdown"></p>
</div>
Using code:
var to = "";
for(var b = 0; b<cred.length; b++){
to += "(" + grade[b] + " x " + cred[b] + ") + ";}
... .getElementById('').innerHTML = to;
Expecting output with cred = [10, 20], grade = [11, 21]:
(10 x 11) + (20 x 21) <-- this expands when arrays have values added to them.
Actual output:
(undefined) <-- doesn't change
I don't have jquery running on my coding platform so javascript code would be really great :)
To do a list of numbered steps, you want to use the ol tag.
Obviously, you'll want to populate the ol tag with li tags :P
Have you tried a simplified version to see if it works? Something like this:
document.getElementById("bdown").innerHTML=to;
Related
I am trying to show the whole array separated with a comma in the HTML body. So far, the whole ArrayList is the result of the multiplication of specific values, so if the value is 2, then ArrayList will be (2,4,6,8,10).
I have created the multiplication function using js and in console, I can see the ArrayList. But whenever I am trying to show this list in HTML using innerHTML, I only can see 10 (for multiplication of 2), but can not visualize the whole list.
function showData() {
var theSelect = demoForm.part;
var secondP = document.getElementById('secondP');
var num = theSelect[theSelect.selectedIndex].value
console.log("this is" + num)
for (var i = 1; i <= 5; i++) {
result = i * num;
console.log("List is" + result);
}
secondP.innerHTML = ('Its Standerd Pack is: ' + theSelect[theSelect.selectedIndex].value + " we have to choose" + result);
}
<p id="secondP"></p>
Current output is:
Its Standard Pack is: 2 we have to choose 10
Expected output:*
Its Standard Pack is: 2 we have to choose 2,4,8,10
Any suggestion on how to do that. Thank you very much
You need to make result an array and push onto it, not reassign it.
function showData() {
var secondP = document.getElementById('secondP');
var num = 2
console.log("this is" + num)
let result = [];
for (var i = 1; i <= 5; i++) {
result.push(i * num);
}
secondP.innerHTML = ('Its Standerd Pack is: ' + num + " we have to choose " + result.join(", "));
}
showData();
<p id="secondP"></p>
Sorry if I got it wrong but if you were having trouble to show the items in an array separated by a comma (or anything else),
the simplest solution I have is arr.join(", ")
or a neat code
const arr = [1, 2, 3, `a`, `b`, `c`];
function showFullArrayList(arr) {
console.log(arr.join(`, `));
}
showFullArrayList(arr);
I've tried to get solutions from Google and earlier asked questions but questions and answers relate to only one select having multiple options. To clarify more, when I generate code for loop to create multiple select on screen and then use JavaScript to get selectedIndex or value and use alert to check if correct value is taken, then only value from selected option from first select table generated through for loop is shown repeated. Kindly find the code below:
<body>
<script>
// JSON code getting g named array throgh JSON.parse method
for (g=0; g<m.length; g++) {
n += " <select id=\"mySelect\" onchange=\"myFunction()\">";
n += " <option> - Select Option - </option>";
n += "<option>A</option>";
n += " <option>B</option>";
n += " <option>C</option>";
n += " <option>D</option>";
n += " </select>";
} // end of for loop
document.getElementById("demo").innerHTML = n;
// in between some code
function myFunction() {
var y = document.getElementById("mySelect");
var j = y.selectedIndex;
var b = y.options[j].text;
alert ("Your answer is: " + b);
} // end of myFunction
</script>
<p id="demo"></p>
</body>
When execute this code, e.g. if (arrayG.length is 5), then select-option is shown on screen five times, is perfect, when we select option from first select-options loop alert shows perfect selected option. e.g. If we select C from first select then alert shows C, but when we select options from other four select elements it still shows C i.e. selected option from first select elements.
We want our code to show right selected options from different 5 select elements generated through above for loop.
Request to kindly help, since we have mined a lot for the answer.
As Cbroe heavily hinted, you need to pass the select element to the method with 'this', then use that reference to find the selected value.
var m = 3;
var n = "";
// JSON code getting g named array throgh JSON.parse method
for(g=0; g<m; g++) {
n += " <select id=\"mySelect"
n += g;
n += "\" onchange=\"myFunction(this)\">";
n += " <option> - Select Option - </option>";
n += "<option>A</option>";
n += " <option>B</option>";
n += " <option>C</option>";
n += " <option>D</option>";
n += " </select>";
} // end of for loop
document.getElementById("demo").innerHTML = n;
// in between some code
function myFunction(element) {
var j = e.selectedIndex;
var b = e.options[j].text;
alert ("Your answer is: " + b);
} // end of myFunction
jsbin demo
Or you could pass the index and find it with the id that way.
var m = 3;
var n = "";
// JSON code getting g named array throgh JSON.parse method
for(g=0; g<m; g++) {
n += " <select id=\"mySelect"
n += g;
n += "\" onchange=\"myFunction(";
n += g;
n += ")\">";
n += " <option> - Select Option - </option>";
n += "<option>A</option>";
n += " <option>B</option>";
n += " <option>C</option>";
n += " <option>D</option>";
n += " </select>";
} // end of for loop
document.getElementById("demo").innerHTML = n;
// in between some code
function myFunction(index) {
var y = document.getElementById("mySelect" + index);
var j = y.selectedIndex;
var b = y.options[j].text;
alert ("Your answer is: " + b);
} // end of myFunction
jsbin demo
It is very clear by your code/question structure that you are not equipped to handle javascript basics. You will need to do some introduction javascript courses otherwise you will continue to struggle a lot, and make a lot of bad code.
I just wanted to display my Array inside of either an div or a heading.
The code i posted down below only displays the last part of the "List".
When i tried to use: document.write instead, everything worked fine.
Is there any special trick to display the list the same way document.write does using my Code below?
var Users = ["Till", "Didi", "Klausi", "Heinz"];
for (var i = 0; i < Users.length; i++) {
document.querySelector("div").innerHTML = Users[i] + " is always on my page " + "<br>";
}
Build the whole HTML first by iterating on the array and concatenating strings. And then set it as innerHTML of the div.
var Users = ["Till", "Didi", "Klausi", "Heinz"];
var _html = "";
for (var i = 0; i < Users.length; i++) {
_html += Users[i] + " is always on my page " + "<br>";
}
document.querySelector("div").innerHTML = _html;
<div></div>
Every time the loop runs it inserts the current iterable item into the HTML, replacing the one previous. So add a variable outside of the loop and append to it using var x += User[i].
var separator = ' is always on my page<br>';
var html = Users.join(separator) + separator;
document.querySelector("div").innerHTML = html;
// writes
// "Till is always on my page<br>Didi is always on my page<br>Klausi is always on my page<br>Heinz is always on my page<br>"
I would like to do something like this with JavaScript. This is my code for creating the first half:
<script>
var numberOfLines = 10;
var str = '*';
var space = ' ';
for (var i = 0; i < numberOfLines; i++){
document.write(str + '<br>');
str = str + "*";
}
</script>
How can I finish it?
You can use Array.join to create your repeated characters. Use a monospaced font to preserve the space width.
document.addEventListener("DOMContentLoaded", function(event) {
var output = "";
var numberOfLines = 10;
for (lineNum = 0; lineNum < numberOfLines; lineNum++) {
output += Array(lineNum + 2).join("*") + Array(((numberOfLines * 2) - (2 * (lineNum))) -1).join(" ") + Array(lineNum + 2).join("*") + "<br>";
}
document.getElementById("result").innerHTML = output;
});
#result {font-family: monospace;}
<div id="result"></div>
This is not perfect but very close:
var numberOfLines = 10;
var str = '*';
var arr = [" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "];
var spaces = arr.join("");
for (var i = 0; i < numberOfLines; i++) {
document.write(str + spaces + str + '<br>');
str = str + "*";
arr.splice(-1,1);
arr.splice(-1,1);
spaces = arr.join("");
}
While simple in concept, there's actually a lot to consider when doing this, so lets analyze your code and build from there.
for (var i = 0; i < numberOfLines; i++) {
document.write(str + '<br');
str = str + "*";
}
this will loop through numberOfLines times. It will also output str numberOfLines times. Each loop, you're printing to the document; however, you would like to add a lot of spaces to str as well as a dynamic number of * characters before printing, and each time it will be a different number of spaces. Therefore, you either need to re-build str on each iteration of the loop, or build the entire string str prior to using document.write()
There are many different ways you can accomplish this, I'll go through two:
With a function
You can create a function to build each line. To do this, your function will need to know a few things:
How many lines will there be?
Which line are we currently on?
What character should you use for the visible parts of the triangle?
What character should you use for the invisible parts of the triangle?
So we can start by creating a function, we'll call it generateTriangleLine.
To generate a line, we will want to look at how many of the visible character we want to show, and how many of the invisible. Because there are two sides to this, we will want to output twice as many characters as the current line number:
function generateTriangleLine(visible, invisible, numberOfLines, currentLine) {
// Let's initialize the line so that it has no characters:
var line = '';
// We want to output twice as many characters as there are lines
// So we will loop from 0 to (but not including) numberOfLines * 2
for (var i=0; i<numberOfLines*2; i++) {
if (i<=currentLine || i>=(2*numberOfLines - currentLine - 1)) {
// If we are at the beginning, or the end of the line, we want to output characters.
// We want to add as many visible characters as the line number we are on!
// At the end of the line, 2*numberOfLines = 20. If currentLine starts at 0,
// we will want to draw one visible character, so we need to subtract one from this.
line += visible;
} else {
// If we aren't at the beginning or end, just add the invisible character.
line += invisible;
}
}
// And we want to return the line:
return line;
}
In our code, we can then loop through numberOfLines times, generating each line using our function:
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
If we run this, we'll get the appropriate output, but it won't necessarily be formatted correctly. This is because most fonts that you read on a daily basis have different widths for each character. The easiest way we can fix this is by wrapping our output in <pre> tags:
document.write('<pre>');
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
document.write('</pre>');
With a nested for loop to generate the entire output
The other approach we can take is exactly the same as with the function above, but instead of calling a function to generate each line, we generate each line within for loops, and then output everything at the end altogether:
// The first loop will be for each line.
for (var i = 0; i < numberOfLines; i++) {
// The nested for loop will be for each character on each line
// Remember, we have twice as many characters as we do lines
for (var x = 0; x < numberOfLines * 2; x++) {
// Just like we did in the function, we want to check
// if we're at the beginning or the end of the line
// Again, we subtract one from the end so that we still output at least one * on
// the first line.
if (x <= i || x >= (numberOfLines*2) - i - 1) {
// If we are at the beginning or end, output the *
str += "*";
} else {
// Otherwise, output the space
str += space;
}
}
str += '<br>';
}
Once again, we will get the correct output; however, we need to adjust for the letter widths so we can wrap our text in <pre> tags.
Keep in mind, there are numerous ways to solve problems with programming. I've only provided a couple of examples. I would highly encourage you to practice by coming up with your own way of doing this using the skills you learn from the various responses!
I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/