<html>
<head>
<script type="text/javascript">
function exe()
{
document.getElementById("cal").addEventListener("click", checkNumber,false);//after the load event,it call this function to register button event
}
function checkNumber()
{enter code here
var number1 = parseInt(document.getElementById("number"));
var number2 = document.getElementById("textbox");
var isPrime = true;
if (isNaN(number1))
number2.value = (number1 + " is not a valid number! Try again!");
else{
if (number1 == 1)
number2.value = (number1 + " is not prime!");
else{
for (var i=2; i<number1; i++){
if (number1 % i == 0){
strong text number2.value = (number2 + " is not prime. It is divisible by " + i + ".");
isPrime = false;
break;
}
}
if (isPrime)
number2.value = (number1 + " is prime!");
}
}
window.addEventListener("load",exe,false);//the first load of the page will execute this function and call function exe()
</script>
</head>
<body>
<form action="#" id="form1">
<h1 align="center">prime number calculator</h1><br>
<input align="center" type="text" size="" name="number" id="number"/><br>
<input type="button" name="cal" id="cal" value="Calculate" />
</form>
<section>
<input align="center" type="text" size="" name="num2" id="textbox"/>
</section>
</body>
</html>
I have studied javascript before this but the method I use is onclick or onload, I've never used addEventListener before, my code didn't function at all. First, when the page loads, I register an event to trigger the other function and register an event for the button, after that I call the other function for further calculation but it wouldn't work at all. I don't know which lines of codes are inappropriate, this condition must use addEventListener.
There are a few mistakes in your code. Here is the corrected version
<html>
<head>
<script ="text/javascript">
function exe()
{
document.getElementById("cal").addEventListener("click", checkNumber,false);//after the load event,it call this function to register button event
}
function checkNumber()
{
var number1 = parseInt(document.getElementById("number").value);
var number2 = document.getElementById("textbox");
var isPrime = true;
if (isNaN(number1))
number2.value = (number1 + " is not a valid number! Try again!");
else{
if (number1 == 1)
number2.value = (number1 + " is not prime!");
else{
for (var i=2; i<number1; i++){
if (number1 % i == 0){
number2.value = (number1 + " is not prime. It is divisible by " + i + ".");
isPrime = false;
break;
}
}
if (isPrime)
number2.value = (number1 + " is prime!");
}
}
}
window.addEventListener("load",exe,false);//the first load of the page will execute this function and call function exe()
</script>
</head>
<body>
<form action="#" id="form1">
<h1 align="center">prime number calculator</h1><br>
<input align="center" type="text" size="" name="number" id="number"/><br>
<input type="button" name="cal" id="cal" value="Calculate" />
</form>
<section>
<input align="center" type="text" size="" name="num2" id="textbox"/>
</section>
</body>
Related
I've got a problem with modifying my code. I need to edit my code so it will not only do its purpose (the thing that it does now) but it will count from 1 to given number.
The code is in Polish and it's simple. It's purpose for now is to calculate the factorial of given number.
Here's the code:
function obliczSilnie(liczba) {
var wynik = silnia(liczba);
if (wynik > 0) {
document.getElementById("result").innerHTML =
"<h3 style'color:blue;'>Silnia liczby " + liczba +
"wynosi: " + wynik + "</h3>";
}
}
function silnia(liczba) {
if (liczba == 0 || liczba == 1) {
return 1;
} else if (liczba < 0) {
error();
return -1;
}
var wynik = liczba * silnia(liczba - 1);
return wynik;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Błąd: Nie można obliczyć silni dla liczby ujemnej! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Obliczanie silni</h1>
<form name="myForm">
<p> <b>Podaj liczbę:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Wyczyść">
<input type="button" value="Obilcz" onclick="obliczSilnie(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>
I hope I understood your question correctly. That's my solution:
function computeFactors(number) {
//Here we use recursion with a for loop
for(var i = 1;i < number;i++){
var result = factorial(i);
if (result > 0) {
document.getElementById("result").innerHTML +=
"<h3 style='color:blue;'> Factorial of " + i +
" is: " + result + "</h3>";
}
}
}
function factorial(number) {
if (number == 0 || number == 1) {
return 1;
} else if (number < 0) {
error();
return -1;
}
var result = number * factorial(number - 1);
return result;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Error: Could not factorize a negative number! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Factory calculation</h1>
<form name="myForm">
<p> <b>Enter a number:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Clear">
<input type="button" value="Calculate" onclick="computeFactors(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>
I've managed to create a form and set a cookie to remember that the user has submitted the form, but the code looks very complicated. Is there not a simpler way to do this? What can I remove? I am NOT SAVING any input data. I just need to ensure that a user fills out the form and is then redirected to the index page. Then when they try to open the page again, they don't have to fill out the form.
<html>
<head>
<title>Document Title</title>
<script type="text/javascript">
cookie_name="landasp"
expdays=365
function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function get_cookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg){
return get_cookie_val(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function get_cookie_val(offset){
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function saving_cookie(){
var expdate = new Date ();
expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000));
Data="cooked"
set_cookie(cookie_name,Data,expdate)
}
function get_cookie_data(){
inf=get_cookie(cookie_name)
if(!inf){
document.getElementById("display1").style.display="block"
}
else{
document.getElementById("display2").style.display="block"
}
}
</script>
</head>
<body onload="get_cookie_data()">
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" onsubmit="saving_cookie()">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</body>
</html>
Yes, the cookie scripts are normally that big. You can externalise them in a jsfile
However if you do not need the cookie on the server, we nowadays use sessionStorage or localStorage
Also reversing the test
NOTE this script completely replaces yours
const cookie_name = "landasp";
window.addEventListener("load", function() {
const inf = localStorage.getItem(cookie_name);
if (inf) {
document.getElementById("display2").style.display = "block"
setTimeout(function() {location.replace("index.html"},2000)
} else {
document.getElementById("display1").style.display = "block"
}
document.getElementById("regForm").addEventListener("submit", function() {
localStorage.setItem(cookie_name, "done");
})
})
adding an ID to the form and removing inline event handlers
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" id="regForm">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</div>
I am trying to make an simple math test that has 10 problems. They have to display one at a time. I have hit a roadblock and I'm not sure how to move forward from here. I made a submit button and I figured I could just load the next question onClick load but it's a little more complicated than I thought.Any advice would be greatly appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top"+i).innerHTML = num1;
document.getElementById("bottom"+i).innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"+i]["answer"+i].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;x++) {
if (document.forms["problem"+i]["answer"+i].value == mathProblem[i]) {
return true;
}
else if(isNaN (document.forms["problem"+i]["answer"+i].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem1">
<input type="text" size="1" name="carry1"><br/>
<label id="top1"></label><br />
<label id="bottom1"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer1">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
I think This above code gives this Error
Uncaught TypeError: Cannot set property 'innerHTML' of null
Because in your code writeProblem() function has mistake, by the time the function call document read only the element with id "top1" another ids are not there but you are repeting the loop 11 times, so change the onload function body according to the standards of Javascript
I have updated the code please check once JS Fiddle
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top").innerHTML = num1;
document.getElementById("bottom").innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"]["answer"].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;i++) {
if (document.forms["problem"]["answer"].value == mathProblem[i]) {
writeProblem();
return true;
}
else if(isNaN (document.forms["problem"]["answer"].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem">
<input type="text" size="1" name="carry1"><br/>
<label id="top"></label><br />
<label id="bottom"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
SOLUTION
Avoid using onload, onclick or any inline event or style (read more)
NOTE: In this solution I'm using classList that aint fully supported.
HTML
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<input id="submit" type="button" value="Submit"/>
CSS
div, input {
width: 60px;
}
label {
float: right;
padding-right: 10px;
}
.invalid {
border: 1px solid red;
}
JS
var mathProblem = [];
var tops = document.getElementsByClassName('top');
var bottoms = document.getElementsByClassName('bottom');
var answers = document.getElementsByClassName('answer');
function writeProblem(){
for (var i=0; i<3; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
tops[i].innerHTML = num1;
bottoms[i].innerHTML = '+' + num2;
mathProblem[i] = num1 + num2;
}
}
window.addEventListener('load', writeProblem);
function submitAnswer(){
var invalid = document.getElementsByClassName('invalid');
for(var i=0; i<invalid.length; i++){
invalid[i].classList.remove('invalid');
}
var correct = 0;
var wrong = 0;
for (var a=0; a<3; a++) {
var answer = answers[a];
if(isNaN(Number(answer.value))){
answer.classList.add('invalid');
alert('This is not a spelling test, please use numbers');
return false;
}
if(answer.value === ''){
answer.classList.add('invalid');
alert('Answer all questions please');
return false;
}
if (Number(answer.value) === mathProblem[a]) {
correct++;
}
else {
answer.classList.add('invalid');
wrong++;
}
}
alert('Correct: ' + correct + '\nWrong: ' + wrong);
}
document.getElementById('submit')
.addEventListener('click', submitAnswer);
I'm making just a simple math learning helper to help me learn javascript. I want to refresh The textbox after a wrong answer(the page refreshes after a right answer to get a new question), but I want the question to be the same if you get it wrong. Here's my code:
<!doctype html>
<body>
<center>
<font size="5">
<form Id="Input">
<input type="text" name="Input">
<input type="button" value="submit" ID="Button">
</form>
<script type="text/javascript">
Button.addEventListener("click", Answer);
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A +B;
var Input = document.getElementById('Input');
document.write(A + "+" + B + "=");
function Answer() {
if(Input.Input.value == C) {
alert("correct!");
window.location.reload();
} else {
alert("incorrect!");
document.getElementById('txtField').value='new value here'
}
}
</script>
</body>
</html>
You just need to give the txtField id to the text input here is a working fiddle http://jsfiddle.net/eFf27/
<input id="txtField" type="text" name="Input">
You forgot to add an ID to your text box.
<!doctype html>
<body>
<center>
<font size="5">
<form Id="Input">
<input id="txtField" type="text" name="Input">
<input type="button" value="submit" ID="Button">
</form>
<script type="text/javascript">
Button.addEventListener("click", Answer);
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A +B;
var Input = document.getElementById('Input');
document.write(A + "+" + B + "=");
function Answer()
{
if(Input.Input.value == C)
{
alert("correct!");
window.location.reload();
}
else
{
alert("incorrect!");
document.getElementById('txtField').value='new value here'
}
}
</script>
</body>
</html>
I have an HTML page where there are two Textboxes and a Button. And I had written a Compute function to display the result in a Textbox but its not working. Alerts are not being fired on the page.
Can any one help me out here, where am i going wrong.
<script type="text/javascript">
function isNumericKey(e)
{
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e)
{
var charCode = e.which;
}
else
{
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function submitMyNumber()
{
alert(1);
var x = document.getElementById('myInput').value;
return x.match(/^[0-9]+$/) != null;
var y = document.getElementById('myInput1').value;
return y.match(/^[0-9]+$/) != null;
compute();
}
function compute()
{
alert(1);
var a,b,c;
var qtc=document.form1.myInput.value;
alert(qtc);
var hr=document.getByElementById('myinput1').value;
alert(hr);
a=60/hr;
alert(a);
b=math.sqrt(a);
alert(b);
c=qtc/b;
alert(c);
document.write(a + "" + b+ " " + c+ "")
}
</script>
</head>
<body>
<form>
<table align="center" style="border:2px solid black">
<tr>
<td>Qtc:</td>
<td><input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br /></td></tr>
<tr>
<td>Hr:</td>
<td><input type="text" id="myInput1" name="myInput1" onkeypress="return isNumericKey(event);" /><br />
</td>
</tr>
<tr>
<td> <input type="submit" id="mySubmit" name="mySubmit" value="Submit only Number" onclick="compute()" />
</td>
</tr>
<tr><td><input type="text" id="result" name="result" value="" /></td></tr>
</table>
</form>
</body>
</html>
in this function
function submitMyNumber() {
var x = document.getElementById('myInput').value;
return x.match(/^[0-9]+$/) != null; // <-- return
var y = document.getElementById('myInput1').value;
return y.match(/^[0-9]+$/) != null;
compute();
}
on the second line the function is returning, so all next lines won't never be executed.
If I have to guess you probably want to do something like
function submitMyNumber() {
var x = document.getElementById('myInput').value;
if (!x.match(/^[0-9]+$/)) { return false }
var y = document.getElementById('myInput1').value;
if (!y.match(/^[0-9]+$/)) { return false }
compute();
}
There are typo errors in your code:
Update: Fiddle
In compute() function
getByElementById('myinput1') should be getElementById('myInput1')
math.sqrt(a); should be Math.sqrt(a);
The function should look like
function compute(){
var a,b,c;
var qtc=document.form1.myInput.value;
alert(qtc);
var hr=document.getElementById('myInput1').value;
alert(hr);
a=60/hr;
alert(a);
b=Math.sqrt(a);
alert(b);
c=qtc/b;
alert(c);
document.write(a + "" + b+ " " + c+ "")
//var result = document.getElementById('result');
//result.value = c;
}
Your html form must have a name=form1 <form name="form1">
<form name="form1">
<table align="center" style="border:2px solid black">
<tr>
<td>Qtc:</td>
<td><input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br /></td>
</tr>
<tr>
<td>Hr:</td>
<td><input type="text" id="myInput1" name="myInput1" onkeypress="return isNumericKey(event);" /><br /></td>
</tr>
<tr>
<td><button type="button" onclick="compute(); return false;">Submit only Number</button></td>
</tr>
<tr><td><input type="text" id="result" name="result" value="" /></td></tr>
</table>
</form>
Possible mistakes in your code
Compute function is never getting called
Result text box value is never set
You dont have a form name in your code :
Change this from <form>
to
<form name = "form1" >
PS:
When you use something like document.form1.myInput.value;
You tell get the myInput value from the form with name form1
Change your return statements to if statements:
function submitMyNumber()
{
alert(1);
var x = document.getElementById('myInput').value;
if (x.match(/^[0-9]+$/) === null ) {
return;
}
var y = document.getElementById('myInput1').value;
if (y.match(/^[0-9]+$/) === null ) {
return;
}
compute();
}
I think Function should be:
function submitMyNumber() {
var x = document.getElementById('myInput').value;
var x_match= x.match(/^[0-9]+$/) != null;
//Store x_match in hiddenfield
var y = document.getElementById('myInput1').value;
var y_match= y.match(/^[0-9]+$/) != null;
//Store y_match in hiddenfield
compute();
return;
}
There are lot of javascript errors in above code i dont know what you are trying to do but correct javascript will be
function compute()
{
alert(1);
var a,b,c;
var qtc=document.form1.myInput.value;
alert(qtc);
var hr=document.getElementById('myInput1').value;
alert(hr);
a=60/hr;
alert(a);
b=Math.sqrt(a);
alert(b);
c=qtc/b;
alert(c);
document.getElementById('result').value = c;
//document.write(a + "" + b+ " " + c+ "")
return false;
}
plus form tag dont have name field. it should be like
<form onsubmit="return false;" name="form1">
and submit button should return false
like
<input type="submit" id="mySubmit" name="mySubmit" value="Submit only Number" onclick="compute(); return false;" />
or else form will continue to submit whether you got javascript error or not
You tool Like firebug to locate your javascript errors