Does not append input strings dynamically on the web page - javascript

I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>

In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()

Related

Issue with getting a keyup function to get sum of input field values using plain Javascript

I'm working on a personal project and I've run into an issue that I haven't been able to solve.
Here is a function that generates new table rows into a table (with id of "tableData") when a button is clicked:
function addNewRow(){
var tableEl = document.getElementById("tableData");
var newLine = '<tr class="newEntry">';
var classArray = ["classA", "classB", "classC", "classD"];
for (var i = 0; i < classArray.length; i++){
newLine += '<td><input class="' + classArray[i] + '"></td>';
}
newLine += '</tr>';
tableEl.insertAdjacentHTML("beforeend", newLine);
}
document.getElementById("addRow").addEventListener("click", addNewRow, false);
//the element with id="addRow" is a button
I've simplified the code for the above function for the sake of readability as it's not the focus of the problem. When the button is clicked, a new row is added successfully.
The problematic part involves another function that takes the sum of the respective classes of each row and displays them in a div.
The goal is to get the sum of the values of all input fields with matching class names. For example, let's say I use the addNewRow function to get six rows. Then I want to have the div showing the sum of the values of all input fields with the class name of "classA"; the number in that div should be the sum of those six values, which gets updated as I type in the values or change the existing values in any of the input fields with class name of "ClassA".
function sumValues(divId, inputClass){
var sumVal = document.getElementsByClassName(inputClass);
var addedUp = 0;
for (var j = 0; j < sumVal.length; j++){
addedUp += Number(sumVal[j].value);
}
document.getElementById(divId).innerHTML = addedUp;
}
Here are a couple (out of several) failed attempts:
document.input.addEventListener("keyup", sumValues("genericDivId", "classA"), false);
document.getElementsByClassName("classA").onkeyup = function(){sumValues("genericDivId", "classA");}
Unfortunately, after scouring the web for a solution and failing to find one, I just added an event listener to a button that, when clicked, would update the div to show the sum of values. Also had to modify the sumValues function to take values from an array rather than accepting arguments.
My question is: How can I modify the code so that the sum value updates as I type in new values or change existing values using pure Javascript (vanilla JS)?
You are very close, document.getElementsByClassName() returns an array of DOM objects, you need to set the onkeyup function for each and every element by looping through that array.
var classA = document.getElementsByClassName('classA'); // this is an array
classA.forEach(function(elem){ // loop through the array
elem.onkeyup = function(){ // elem is a single element
sumValues("genericDivId", "classA");
}
}
Hopefully this fixes your issue
Maybe the example below is not same with your situation, but you'll get the logic, easily. Anyway, do not hesitate to ask for more guide.
document.getElementById("row_adder").addEventListener("click", function() {
var t = document.getElementById("my_table");
var r = t.insertRow(-1); // adds rows to bottom - change it to 0 for top
var c = r.insertCell(0);
c.innerHTML = "<input class='not_important_with_that_way' type='number' value='0' onchange='calculate_sum()'></input>";
});
function calculate_sum() {
var sum = ([].slice.call(document.querySelectorAll("[type=number]"))).map(e=>parseFloat(e.value)).reduce((a, b) => a+b);
document.getElementById("sum").innerHTML = sum;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<p>
<strong>Sum</strong>:<span id="sum">0</span>
</p>
</div>
<button id="row_adder">
Click me
</button>
<table id="my_table">
</table>
</body>
</html>

Print a given sentence , given times, using javascript

i'm new to programming, wanted to practice.
I wanted to make an html document with javascript embedded, the document will have two input fields in one field the user will type the sentence and in the second field she will type how many times she wanna print it, than when she click on the button the script will print that text in the "printhere" div.
i tried but failed, following is my code, can someone please tell me what i am messing ?
<html>
<body>
<!-- form started -->
<form>
<!-- what sentence to print -->
What to write?<br>
<input id="what"><br><br>
<!-- how many times to print -->
How many times ?<br>
<input id="howmany"><br><br>
<!-- the button -->
<button type="button" onclick="printItNow()">Print Now</button>
<form>
<!-- form ended -->
<!-- the div where the content will print -->
<div id="printhere">
</div>
<script>
function printItNow() {
var printhere = document.getElementById('printhere');
var whatto = document.getElementById('what');
var howmany = document.getElementById('howmany');
for (var i=0; i<howmany; i++) {
printhere.innerHTML += whatto;
}
}
</script>
</body>
<html>
thank you all. :)
you missed .value, in document.getElementById(), change:
var whatto = document.getElementById('what');
var howmany = document.getElementById('howmany');
to
var whatto = document.getElementById('what').value;
var howmany = document.getElementById('howmany').value;
Change
var whatto = document.getElementById('what');
to
var whatto = document.getElementById('what').value;
var howmany = document.getElementById('howmany');
to
var howmany = document.getElementById('howmany').value;
and
printhere.innerHTML += whatto;
to
printhere.innerHTML += whatto+"<br>";
the third change is not must technically , but it will put every sentence on its own line.

How to get label's id?

This is index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="add.js"></script>
<script language="javascript" type="text/javascript" src="get.js"></script>
</head>
<body>
<div id="list">
<form id="programs" name="programs">
</form>
<input type="button" value="add" onClick="add();" />
<input type="button" value="delete" onClick="get();" />
</div>
</body>
</html>
This is add.js
var program_number = 0;
function add()
{
var program_name = "program_sample";
var formID = document.getElementById("programs");
var labelTag = document.createElement("label");
var inputTag = document.createElement("input");
var txtNode = document.createTextNode("program " + program_number);
var brTag = document.createElement("br");
// set input attribute
inputTag.setAttribute("type", "checkbox");
inputTag.setAttribute("name", program_name);
inputTag.setAttribute("value", "program" + program_number);
// set label attribute
labelTag.setAttribute("id", "program_label" + program_number);
labelTag.appendChild(inputTag);
labelTag.appendChild(txtNode);
labelTag.appendChild(brTag);
formID.appendChild(labelTag);
program_number++;
}
This is get.js
function get()
{
var programs = document.programs;
for(var i = 0; i < programs.length; i++)
console.log(programs[i].id);
}
Hello, I want to get the label's id dynamically. add.js code makes it. (below)
<label id="program_label0>
<input type="checkbox" name="program_sample" value="program0" />
program 0<\br>
</label>
If those run normally, the result can be "program_label1", "program_label2", "program_label3" ...
but the result of get.js is just a blank. What should I do to get label's id ..?
or Where my code is wrong ..?
Inside your 'get.js' you could try either
var programs = document.getElementById("programs");
or
var programs = document.forms["programs"];
or
var programs = document.forms[0];
The last one will work only if the form you are referring to is only presented first inside DOM tree.
I see a few problems:
Inputs in the beginning html are outside the form...(Please refer to w3schools form basics)
Instead of inputTag.setAttribute("type", "checkbox");, you should use inputTage.type = "checkbox";
There is no such thing as documents.programs. To access your programs DOM element, please do as in your add.js and document.getElementById("programs");
You do not seem clear on how basics work. - var formID = document.getElementById("programs"); will not return a formID... will return a DOM element. Please read more basic tutorials. Start at - w3schools
First: Why are you using setAttribute over setting the properties?
Second:
var programs = document.getElementById("programs");
More than likely you mean to access window.programs in your code, which only works had that element been in the document when you loaded the page.
When you create an element and add it to the DOM, it does not update the global object (here called window), with that new property name.
You should access form element with `document.programs.elements[i]. So you have missed "elements" which is collection of form elements.

Javascript - How do you set the value of a button with an element from an array?

<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]);

Is there a way to display content on same page after a button is clicked?

I am trying to get my content to display on the same page as my button. But when i enter the values and press display the square i am forming is displayed on a new white webpage.
I ask the user to enter two values (height and width), I also ask for a character to form the border of the square, but i have not been able to do that part yet so i just hard coded a # character in for the border in the meantime
What i would like to know is how to display my square on the same page and not in a seperate page.
I use an external JavaScript file: Here is its code. Its named "SquareScript.js":
function Display()
{
var a = document.getElementById("value1").value;
var b = document.getElementById("value2").value;
var outputText = "";
for (var i = 0; i < a; i++)
{
outputText += "#";
}
outputText +="<br>";
for (var r = 0; r < b; r++)
{
outputText += "#";
for(var p = 0; p < a-2; p++)
{
outputText +="&nbsp&nbsp";
}
outputText += "#";
outputText +="<br>";
}
for (var i = 0; i < a; i++)
{
outputText += "#";
}
}
Here is my webpages code:
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "Assignment3.css">
<style>
table {background-color:white;color:black;}
body {background-image: url('squares.png');}
</style>
</head>
<body>
<div class = "heading">
<h1><img src = "Interested.png" width = 100px height = 100px></img>WELCOME TO BUILD A SQUARE</h1>
</div>
<script src = "SquareScript.js">
</script>
<table>
<tr>
<td>
Please Enter value number 1:&nbsp&nbsp<input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:&nbsp&nbsp<input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Please Enter a character:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type = "text" id = "character">
</td>
</tr>
<tr>
<td>
<button onclick = "Display()">Display</button>
</td>
</tr>
<div id="output" style = "background-color:blue;"><script>
document.getElementById("output").innerHTML(outputText);
</script></div>
</table>
</body>
</html>
Any useful tips will be appreciated and please consider the fact that I am still new to web development so my code is obviously very basic. Please let me know if you require anything more of me.
The way document.write() works is that when it's called outside the HTML page, it automatically creates a new document and writes into that (see the documentation). This is what's going on in your case: the function is called outside of the HTML (in SquareScript.js) and so it's making a new document, which is the "new white webpage" you're seeing.
You could solve this problem by calling document.write() from within the HTML page. Or you could forego using document.write() and instead reference an element on the existing page (a more flexible solution). By creating a new element in your HTML where the output of your functions should appear (like <div id="output"></div>), you can use document.getElementById("output") to put your script's output into that element.
You don't need to call this every time you want to add content. Instead, create a new variable to hold your output text as you generate it.
var outputText = "";
Then as you go through your loops, you can add to outputText:
for (var i = 0; i < a; i++) {
outputText += "#";
}
Then after all your loops are complete, you can insert the content into the output div by making the following function call as the last thing in your display() function:
document.getElementById("output").innerHTML(outputText);
Do not use document.write. Create <div id="result"></div> on your page and place your output there. You should create a string variable containing your HTML output. Then you can display this HTML using the following code:
document.getElementById("result").innerHTML = my_html_output;

Categories