I am working on task using javascript in table.I am trying to add order-list but stuck in that code. when clicking a button a table is displaying that i have achieve.but the thing it should display with numericals i need to add order-list also.Please anyone who can help me to solve these.Taking Inspiration from here, But my code is not working codepen.Please someone point me in right direction.
Output:
Thanks in Advance.
<html>
<head></head>
<body>
<h3>JavaScript Programming</h3>
<hr/>
<input type="button" onclick="f1()" value="Get Data" />
<br/>
<br/>
<table id="table1" border="2">
</table>
<script>
function f1() {
var ar = ["HTML5", "CSS3", "JavaScript", "Angular JS", "Node JS", "Express JS"];
var str = "";
for(var i in ar)
{
str = str + "<tr><td>" + ar[i] + " </td> </tr>";
}
var obj = document.getElementById("table1");
obj.innerHTML = str;
}
</script>
</body>
</html>
you must first define listOfList as array
const listOfList = []
and second change element by ar[i]
listOfList.push("<li>" + ar[i] + "</li>");
function f1() {
const listOfList = [];
const ar = ["HTML5", "CSS3", "JavaScript", "Angular JS", "Node JS", "Express JS"];
let str = "";
for (let i in ar) {
str = str + "<tr><td>" + (+i+1)+ "."+ ar[i] + " </td> </tr>";
listOfList.push("<li>" + ar[i] + "</li>");
}
const obj = document.getElementById("table1");
obj.innerHTML = str;
}
<html>
<head></head>
<body>
<h3>JavaScript Programming</h3>
<hr/>
<input type="button" onclick="f1()" value="Get Data" />
<br/>
<br/>
<table id="table1" border="2"></table>
</body>
</html>
Related
I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>
I am new to HTML and Javascript. I am trying to make a simple website that counts up yes and no votes. I want to display the number of votes for each. The results should be updated after each vote. When I enter a vote, it gets updated for a split second then reverts back to 0,0,0. How do I resolve this?
var yes = 0;
var no = 0;
function clickYes() {
yes++;
alert("You pressed yes");
refreshResults();
}
function clickNo() {
no++;
alert("You pressed no");
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<!DOCTYPE html>
<html>
<script src="voteCount.js" type="text/javascript"></script>
<head>
<h1>This Website Counts Up Votes</h1>
</head>
<body>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="radio" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="radio" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results">
<script>
refreshResults();
</script>
</h3>
</html>
Hi Try to remove script tag from your html file.
its working fine for me.
Hope this helps...
var yes = 0;
var no = 0;
function clickYes() {
yes++;
refreshResults();
}
function clickNo() {
no++;
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<!DOCTYPE html>
<html>
<script src="voteCount.js" type="text/javascript"></script>
<head>
<h1>This Website Counts Up Votes</h1>
</head>
<body>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="radio" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="radio" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results">
</html>
The main problem is button is reloading the page. Either give type="button" or you need to prevent the default event. Also there are few issues:
You haven't closed the </body>.
You cannot have <h1> inside <head>!
Button's type should be either of button, submit or reset, which defaults to submit.
You cannot have a <script> tag, that way how you have used it.
Working Snippet with the alert.
var yes = 0;
var no = 0;
function clickYes() {
yes++;
alert("You pressed yes");
refreshResults();
}
function clickNo() {
no++;
alert("You pressed no");
refreshResults();
}
function refreshResults() {
var results = document.getElementById('results');
results.innerHTML = "Total: " + (yes + no);
results.innerHTML += "<br>Yes: " + yes;
results.innerHTML += "<br>No: " + no;
}
<h1>This Website Counts Up Votes</h1>
<div id="userInput">
<h2>Yes or No?</h2>
<form>
<button type="button" onclick="clickYes()" id="yesbutton">Yes</button>
<button type="button" onclick="clickNo()" id="nobutton">No</button>
</form>
</div>
<h3 id="results"></h3>
try this
function refreshResults() {
var results = document.getElementById('results');
var output = "Total: " + (yes + no);
output += "<br>Yes: " + yes;
output += "<br>No: " + no;
results.innerHTML = output;
}
I'm working with the local storage for the first time and going through some JS tutorials online as I'm quite rusty. Making a dictionary where you can add words in 2 idioms then it displays. Everything is working fine with the exception of the second item in the object "dict", is not being shown although it's in the object. it shows in the console output. Might be the indexing in the loop. Cannot see it though. Any light shed will be appreciated.
function getDictionary(){
var dict = {},
dictStr = localStorage.getItem('dictionary');
if(dictStr !== null){
dict = JSON.parse(dictStr);
}
return dict;
}
function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";
resultOutput.innerHTML = html;
var buttons = document.getElementsByClassName('removeBtn');
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click',remove);
}
}
console.log("");
console.log("All words: "+ JSON.stringify(dict));
}
HTML
...
<p id="sayHello"></p>
<fieldset id="translateField">
<legend> Translate english to Portuguese</legend>
<input type="text" id="newWordEng" name="newWordEng" value="" placeholder=" write the english word" >
<input type="text" id="newWordPt" name="newWordPt" value="" placeholder=" write the portuguese word">
<input type="button" id="addWordBtn" name="addWordBtn" value="Add New Word">
</form>
</fieldset>
<div id="resultOutput">
</div>
<script src="src/translate.js"></script>
</body>
I think it's because you're using the variable "i" twice. In the inner for loop, try using "j" instead:
for(var j = 0; j < buttons.length; j++){
buttons[j].addEventListener('click',remove);
}
Edit: In fact, you can probably remove the inner loop altogether, and just do:
function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";
resultOutput.innerHTML = html;
var buttons = document.getElementsByClassName('removeBtn');
buttons[i].addEventListener('click',remove);
}
}
I am trying to write a JavaScript code to add multiple rows according to the number submited in an input text box. I am trying to do that by using a FOR loop but for some reason it does not work. Can you explain to me why it does not insert as many rows as the value from input text box??? Here is my code:
<!DOCTYPE html>
<html>
<head>
<br><meta charset=utf-8 />
<title>Insert rows in a Table</title>
</head>
<body>
<table id="table" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table><br>
<form>
Type in a number:<input id="input" type="text" value=""}>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form><br/>
<p id="p"></p>
<script>
var tableId = document.getElementById("table");
function insert_Row(){
var input = document.getElementById("input").value;
var number = Number(input);
for(i=0;i<number;i++){
var ii = i+1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(i);
var newTD2 = newTR.insertCell(ii);
newTD1.innerHTML = "Row " + i + " Cell "+ i;
newTD2.innerHTML = "Row " + i + " Cell "+ ii;
};
};
</script>
</body>
</html>
The problem is irrespective of the row number, cells should start from 0,1,2 and so on which is not happening in your code. For the 0th iteration your code works fine, but later on, the cells do not start from 0. Hence the problem
Fix: Since you plan to have only 2 cells for each row, do it like this:
var tableId = document.getElementById("table");
function insert_Row() {
var input = document.getElementById("input").value;
var number = Number(input);
for (i = 0; i < number; i++) {
var j = 0; // First Cell
var k = 1; // Second Cell
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(j);
newTD1.innerHTML = "Row " + i + " Cell " + j;
var newTD2 = newTR.insertCell(k);
newTD2.innerHTML = "Row " + i + " Cell " + k;
};
};
<table id="table" border="1">
</table>
<br>
<form>
Type in a number:
<input id="input" type="text" value=""/>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form>
<br/>
<p id="p"></p>
The issue is with your document.getElementById declarations.
Also, it sounds like you want to insert the rows at the end of your table. In which case, your code will look like this.
var table = document.getElementById("table");
var numRows = document.querySelectorAll("tr").length;
function insert_Row(){
var input = document.getElementById("myInput").value;
var number = Number(input);
for (var i = numRows; i < number; i++) {
var ii = 0;
var ij = 1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(ii);
var newTD2 = newTR.insertCell(ij);
newTD1.innerHTML = "Row " + (i + 1) + " Cell "+ (ii +1);
newTD2.innerHTML = "Row " + (i + 1) + " Cell "+ (ij + 1);
};
};
To use document.getElementById, you need to add an id attribute to your input tag like so.
<input id="myInput" type="button" onclick="insert_Row()" value="add row(s)">
Here is the updated fiddle
http://jsfiddle.net/vgwk00zm/2/
This is my whole html page
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
str.split(" ");
document.write("testing1");
var length = str.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(str[i].charAt(str[i].length - 1) != ".")
{
str[i] = str[i] + ".";
}
str[i] = str[i] + " ";
str[i].charAt(0) = str[i].charAt(0).toUpperCase();
newn = newn + str[i];
}
document.write(newn);
document.write("testing");
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
The html is being displayed correctly, but the button does not produce any action. I even tried document.write("testing") below the loop in the javascript, which had no effect, which makes me think the function is not being called at all. The idea of the function is to format the input string to capitalise the first letter of each word, and put a period after each word.
This is my first time trying to use javascript, so possibly I'm doing something wrong that should be obvious?
final solution:
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
var strn = str.split(" ");
var length = strn.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(strn[i].charAt(strn[i].length - 1) != ".")
{
strn[i] = strn[i] + ".";
}
strn[i] = strn[i].charAt(0).toUpperCase() + strn[i].slice(1);
strn[i] = strn[i] + " ";
newn = newn + strn[i];
}
document.write(newn);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
This should work. Also, echoing The comments before about using new as a variable.
<html>
<head>
<title> text conversion</title>
<script language="JavaScript">
function testResults(form)
{
var str = form.stringn.value;
var newString = "";
var strList = str.split(" ");
for(var i = 0; i < strList.length; i++){
newWord = strList[i].charAt(0).toUpperCase() + strList[i].slice(1) + ".";
newString += newWord + " ";
}
document.write(newString);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
Set <script type="text/javascript"> in your <head>!