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);
Related
This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>
I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>
I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>
Ive stared to learn Javascript, im trying to create a calculator, which just multiplies 2 numbers, i get this error in my browser console.
Can anybody help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a = 0 || b = 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
Firstly, if you are going to do any math with text input, you have to convert them to a number. You can use parseInt(num, 10) or parseFloat(num).
Secondly, in one of your if-statements, you are not actually comparing the variables a and b, but assigning 0 to them. Use two equal signs == to compare variables.
Thirdly, you could just check for whether they are numbers instead using isNaN(num). Doing so would eliminate the first if-statement.
function res() {
var a = parseFloat(document.getElementById("first").value);
var b = parseFloat(document.getElementById("second").value);
var span = document.getElementById("span");
if (isNaN(a) || isNaN(b)) {
span.innerHTML = "0";
}
else {
span.innerHTML = a * b;
}
}
<input type="number" id="first">*
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
check here your corrected code
<html>
<head>
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a == 0 || b == 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
I have this html code with javascript. My average value displays correctly but my find minimum is not displaying anything. Its supposed to show when the user clicks on the find min button on the box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateGrade = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) ) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("average").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if ( (exam1<exam2) && (exam1<exam3)){
$("mini").value=exam1;}
else if ((exam2<exam1) && (exam2<exam3)){
$("mini").value=exam2;}
else {
$("mini").value=exam3;
}
}
window.onload = function () {
$("calculate").onclick = calculateGrade;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Average</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="average"disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var average = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("result").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
} else {
$("result").value = Math.min(exam1,exam2,exam3);
}
}
window.onload = function () {
$("average").onclick = average;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="result" disabled ><br>
<label> </label>
<input type="button" id="average" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
The issue is with the min function. Instead of setting the value of textbox (probably, missing in your code example) you are setting the value of button "mini" (which is incorrect).
Update:
You need to be including one more textbox <input type="text" id="txtMin" disabled ><br>
and update your min function to set the value of it, as follows:
$("txtMin").value=exam1;
...
$("txtMin").value=exam2;
...
$("txtMin").value=exam3;