I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>
I am new to JavaScript. What I am trying to do is make a div and inside of it there will be another div. Within my script code I am trying to create new instances of that div using factory function if that is the right name for it, and then change the innerHTML of the child div if that is possible. Thanks in advance.
<div class = "loopBlock" style="width:350px;">
<fieldset>
<legend style="color:black;font-weight:bold;">While Loop</legend>
<table>
<tr>
<td>Condition:</td>
<td><input type="text" /></td>
</tr>
</table>
<div class = "codeDivClass" id = "codeDiv">
HelloWorld!
</div>
</fieldset>
</div>
<script>
var loopDiv = document.getElementsByClassName("loopBlock");
var loopi =1;
function loopObject(){
var loopDivObject = document.createElement("div");
loopDivObject.innerHTML = loopDiv[0].innerHTML;
loopDivObject.className = "loopBlock";
loopDivObject.id = "loopBlock"+loopi;
loopi++;
return loopDivObject;
};
var functionCodeDiv = document.getElementById("codeDiv");
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
var id = "loopBlock"+i+1;
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
}
</script>
Didn't really get how it should work, but I'm sure I've found a mistake.
var id = "loopBlock"+i+1;
you have to replace with:
var id = "loopBlock"+(i+1);
Example i is 2.
In first case you get: "loopBlock21"
In second (my) case, you'll get "loopBlock3"
The problem is in operator precedence. Since in this line
var id = "loopBlock" + i + 1;
you have two + (unary plus) operators with the same precedence they will act as a string concatenation operators, because one of the operands is a string ("loopBlock").
In your case you want to group i + 1 with parentheses to make the expression evaluate first as arithmetic addition operator. After that string concatenation with "loopBlock" will produce expected result:
var id = "loopBlock" + (i + 1);
Demo: http://jsfiddle.net/0091n9tt/
I think you're problem in is this line:
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
What you are actually doing is trying to gett divs inside the newly created div (loopBlock), which is empty.
You already have a reference to the block you want to modify the innerHTML; you can simply use it like this:
tempLoop.innerHTML = "bye";
So you're for loop would look like this:
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
tempLoop.innerHTML = "bye";
}
Note that you don't need the id anymore.
I am completely new to HTML and JavaScript and I am completely lost.
I am trying to create a to do list where input adds to the top of the list, and when an item in the list is clicked, it is removed.
I am trying to avoid using JQuery or anything outside of pure js.
<!DOCTYPE html>
<html>
<script type="text/JavaScript">
var number_of_items = 0;
var list = [];
var list_container = document.createElement("div");
list_container.id = "container";
function makelist(){
list_container.innerHTML = "";
list.unshift(document.getElementById("todo").value);
++number_of_items;
document.getElementsByTagName("body")[0].appendChild(list_container);
var list_element = document.createElement("ul");
list_container.appendChild(list_element);
for( var i=0 ; i < number_of_items ; ++i){
var list_item = document.createElement("li");
list_item.innerHTML = list[i];
//The problem is here
list_item.onClick = function(){
alert("working");
list.splice(i, 1);
--number_of_items;
makelist();
}
list_element.appendChild(list_item);
}
}
</script>
<body>
Todo: <input type="text" id="todo">
<input type="button" value="Submit" onclick="makelist()" />
</body>
</html>
The problem is, the list_item onclick function never activates. Why?
I apologize in advance for any problems with the way I stated my question.
http://jsbin.com/wicopu/1/edit
use onclick instead of onClick...
or even better ... use event listeners
<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);
I'm trying to replace every instance of "Administrator" on my page with "Admin" Or something similar to that. How would I replace that? If it helps, the span is inside an tag that has the class "user-title".
Like this page but I kinda need to be fed the answer. This is my first time working with javascript.
<ul class="author-ident">
<li class="username">
<a title="Go to Different55's profile" href="http://fwin.co.cc/pun/profile.php?id=2">Different55</a>
</li>
<li class="usertitle">
<span>Administrator</span>
</li>
<li class="userstatus">
<span>Online</span>
</li>
</ul>
I work mostly with JQuery so I can only give you a JQuery solution of the top of my head. Sorry if this is not an option for you. With JQuery you could do this...
$(".user-title").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
NOTE: If you expect more than one instance of "Administrator" per span tag then you will need to do a regex replace like follows...
.replace(/Administrator/g, "Admin");
See this for more info on the regex flag (e.g. "g" means global - more than one)
EDIT: Here is a javascript version....
var spans = document.getElementsByClassName("user-title");
for (var i = 0; i < spans.length; i++)
{
spans[i].innerHTML = spans[i].innerHTML.replace(/Administrator/g, "Admin");
}
ANSWER: This is based on your provided sample HTML (note that I have changed the class name "usertitle" based on your html, check if this is correct)...
var parents = document.getElementsByClassName("usertitle");
for (var i = 0; i < parents.length; i++)
{
var spans = parents[i].getElementsByTagName("span");
for(var j = 0; j < spans.length; j++){
spans[j].innerHTML = spans[j].innerHTML.replace(/Administrator/g, "Admin");
}
}
The JQuery equivalent...
$(".usertitle span").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
<script type="text/javascript">
function changeText(){
document.getElementById('anId').innerHTML = 'my friend';
}
</script>
<p>Welcome to the site <b id='anId'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This will change the content of that .
You can run JS that will look in every span and, if you find "administrator", that you can be use that snippet of code.
To do the replacement you mentioned (replacing all occurrences of Administrator with Admin inside all spans inside .user-title, use:
$('.user-title span').each(function() {
$(this).html($(this).html().replace(/Administrator/g, 'Admin'));
});
NOTE: Assuming you are using jQuery in your app
You can use this function :
function correct() {
var a = document.getElementsByClassName("user-title");
var i = 0;
for(i=0; i<a.length; i++) {
while((a[i].innerHTML).indexOf("Administrator") >= 0){
a[i].innerHTML = a[i].innerHTML.replace(/Administrator/g, 'Admin');
}
}
}
this function will get collection of all elements having class name as "user-title". then the n in for loop, we will access each element in collection, see if it's innerHTML has the word that you want to replace and if it has, we replace it.
Put all instances of the word "Administrator" into a <span> with a certain class, f.i.:
<span class="user_type">Administrator</span>
Then you can use jQuery to do:
$("span.user_type").html("Admin");
Note that this may not be the nicest thing to do but we don't have any other details on what you're trying to accomplish.