javascript function not being called/not working from html form - javascript

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>!

Related

Javascript: Orderlist items In Table

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>

Javascript; html form; user input; display input

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>

Return Output function javascript inner html

I want to output a function secret(); so it will look like this:
AAAA-BBB-<random string>
But it returns this error:
Uncaught TypeError: secret is not a function
Here is the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Random End String</title>
<script type="text/javascript">
function writeName() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret = secret();
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + secret + "";
formContent.innerHTML = "";
}
</script>
<script>
function secret() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
</script>
</head>
<body>
<p id="welcome"></p>
<form id="entername">
Your Name:<input type="text" id="name" /><br/> LockerID:
<input type="text" id="alamat" /><br/>
<input type="hidden" id="secret">
<input type="button" value="Submit" onclick="writeName();" />
</form>
</body>
</html>
Don't name the var secret change it to something else in this example secret1 works fine'.
EDIT: You also need to return your "secret text".
Full working example:
function writeName() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret1 = secret();
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + secret1 + "";
formContent.innerHTML = "";
}
function secret() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text
}
function writeName1() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + text + "";
formContent.innerHTML = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Random End String</title>
</head>
<body>
<p id="welcome"></p>
<form id="entername">
Your Name:<input type="text" id="name" /><br/> LockerID:
<input type="text" id="alamat" /><br/>
<input type="hidden" id="secret">
<input type="button" value="Submit" onclick="writeName();" />
</form>
</body>
</html>
Your Name:<input type="text" id="name1" /><br/> LockerID:
<input type="text" id="alama1t" /><br/>
<input type="hidden" id="secret1">
<input type="button" value="Submit" onclick="writeName1();" />
Your local variable secret is hiding your function secret. Simply rename the variable to something else to fix this issue
function writeName(){
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret = secret(); //right here this is your issue
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is "+name.value+"-"+alamat.value+"-"+secret+"";
formContent.innerHTML = "";
}

How do I display results?

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;
}

JS - How to start from new line inside for loop?

I am trying to print 6 random numbers after clicking a button. Then every time I click the button again, random numbers should start from new line however I do not know how. I tried everything and nothing works. I appreciate any help.
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
<!DOCTYPE html>
<html>
<head>
<title>Let's ROLL!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
input, button {display: block;}
</style>
<script>
var number = "";
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
</script>
</head>
<body>
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
</body>
</html>
Not 100% clear on where you wanted the breaks, but in a text area, a line break is \n. If this was in an HTML element, you would use <br />.
var number = "";
function fname() {
for (i = 1; i <= 6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
}
number = number + "\n";
var print = number + "GOOD LUCK!";
document.getElementById("total").value = print;
}
input,
button {
display: block;
}
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
Add "\n".
I am assuming you want to concatenate the new text in the text area, so you should use += instead of =:
document.getElementById("total").value += print + "\n";
You can use arrays and .join() the numbers and lines together by their appropriate delimiters. This only inserts the characters between the elements. \n in a string renders a new line.
var button = document.getElementById('roll');
var total = document.getElementById('total');
var rolls = [];
button.onclick = function() {
var roll = [];
for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1));
rolls.push(roll.join('-'));
total.value = rolls.join('\n') + "\nGOOD LUCK!";
}
<button id="roll">ROLL!</button><br>
<textarea id="total" rows="12" cols="50" readonly></textarea>

Categories