Javascript to jquery conversion - javascript

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>

Related

JS and jQuery Address Book - search function not working (amongst other problems)

I'm very new to the development world (2 months) and I'm trying to get into a selective coding bootcamp. They've asked me to build an addressbook in JS, using HTML, CSS and jQuery, as part of the admissions process. I think I'm pretty close but I can't get my solution to do exactly what it needs.
So this is what I've got so far in JS/jQuery:
// creating an address book constructor, which will contain all our contacts
function AddressBook() {
this.contacts = [];
}
// creating function that adds contacts to the array
AddressBook.prototype.addContact = function (contactToAdd) {
this.contacts[this.contacts.length] = contactToAdd;
};
// creating a contact search function
AddressBook.prototype.searchContact = function (searchTerm) {
for (let i = 0; i < this.contacts.length; i++) {
if (
searchTerm === this.contacts[i].firstName ||
this.contacts[i].lastName ||
this.contacts[i].phoneNumber ||
this.contacts[i].address
) {
return this.contacts[i];
}
return false;
}
};
//creating a delete function
AddressBook.prototype.deleteContact = function (contactToDelete) {
for (let i = 0; i < this.contacts.length; i++) {
if (contactToDelete === this.contacts[i]) {
delete this.contacts[i];
}
}
};
// creating contacts as objects with certain properties and values
function Contact(firstName, lastName, phoneNumber, address) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.address = address;
}
function displayContacts(addressBookDisplay) {
let htmlForTable = "";
for (let i = 0; i < addressBookDisplay.contacts.length; i++) {
const contact = addressBookDisplay.contacts[i];
htmlForTable +=
"<tr>" +
"<td>" +
contact.firstName +
"</td>" +
"<td>" +
contact.lastName +
"</td>" +
"<td>" +
contact.phoneNumber +
"</td>" +
"<td>" +
contact.address +
"</td>" +
"</tr>";
}
$("#contact-table-start").html(htmlForTable).appendTo("table");
}
function showContact(contact) {
if (contact !== undefined) {
$("#show-search-results").show();
const contactFirst = contact.firstName;
const contactLast = contact.lastName;
const contactPhone = contact.phoneNumber;
const contactAddress = contact.address;
$(".first-name").text(contactFirst);
$(".last-name").text(contactLast);
$(".phone-number").text(contactPhone);
$(".address").text(contactAddress);
let button = $("#delete-button");
button.empty();
button.attr("name", contactFirst);
button.append("<button class='deleteButton'>Delete</button>");
} else {
$("#yes-results").hide();
$("#no-results").text("No result matches your search, try again?");
}
}
let addressBook = new AddressBook();
$(document).ready(function () {
$("#add-form").on("submit", function (event) {
event.preventDefault();
// creating variables storing input from addform
const firstNameForm = $("[name=new-first-name]").val();
const lastNameForm = $("[name=new-last-name]").val();
const phoneNumberForm = $("[name=new-phone-number]").val();
const addressForm = $("[name=new-address]").val();
$("[name=new-first-name]").val("");
$("[name=new-last-name]").val("");
$("[name=new-phone-number]").val("");
$("[name=new-address]").val("");
let newContact = new Contact(
firstNameForm,
lastNameForm,
phoneNumberForm,
addressForm
);
addressBook.addContact(newContact);
displayContacts(addressBook);
});
});
$(document).ready(function () {
$("#search-form").on("submit", function (event) {
event.preventDefault();
// creating variables storing input from searchform
const searchForm = $("[name=searchterm]").val();
$("[name=searchterm]").val("");
const searchcontact = addressBook.searchContact(searchForm);
showContact(searchcontact);
});
});
$(document).ready(function () {
$("#delete-button").on("click", function (event) {
event.preventDefault();
let contactDelFirst = $("#delete-button").attr("name");
let contactToDelete = searchContact(contactDelFirst);
addressBook.deleteContact(contactToDelete);
showContact(contactToDelete);
});
});
This is my HTML if needed:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Elise's Address Book</title>
<link href="./Style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="./Script.js"></script>
</head>
<body>
<header>
<h1>Elise's Address Book</h1>
</header>
<main>
<section>
<div id="search-contact">
<h2>Search Contacts</h2>
<form action="#" id="search-form">
<div>
<input
type="text"
name="searchterm"
placeholder="Enter contact's full name"
/>
<input type="submit" />
</div>
</form>
</div>
<div id="show-search-results">
<div id="yes-results">
<h2>Your Contact</h2>
<p>First Name: <span class="first-name"></span></p>
<p>Last Name: <span class="last-name"></span></p>
<p>Phone Number: <span class="phone-number"></span></p>
<p>Address: <span class="address"></span></p>
<div id="delete-button"></div>
</div>
<div id="no-results">
<span></span>
</div>
</div>
<div id="contact-list">
<h2>All Contacts</h2>
<table id="contact-table-start">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
</table>
</div>
<div id="add-contact">
<h2>Add New Contact</h2>
<form action="#" id="add-form">
<div>
<input
type="text"
name="new-first-name"
placeholder="Enter first name"
required
/>
<input
type="text"
name="new-last-name"
placeholder="Enter last name"
required
/>
<input
type="text"
name="new-phone-number"
placeholder="Enter phone number (incl. country code)"
pattern="^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"
required
/>
<!--check pattern-->
<input
type="text"
name="new-address"
placeholder="Enter address"
required
/>
<input type="submit" />
</div>
</form>
</div>
</section>
</main>
<footer>
<p>Coded by <em>Elise Verhoeye</em></p>
</footer>
</body>
</html>
My main concerns are:
My search function isn't working as it should, it only ever outputs the first element in the array of contacts.
The new contacts I am adding are being added into the first column, so it's a table within a table, even though my new HTML has td (table data) elements in it.
Does anyone know how I can get this fixed?
Many thanks in advance!

Add elements With innerHTML and onclick event

start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>challenge</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="selector.css" />
</head>
<body>
<header>
<h1>challenge 2 </h1>
<h2>Create an HTML select</h2>
</header>
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
<script src="selector.js"></script>
</body>
</html>
It is supposed to create a new <option> for my <select>, but it executes for 1s only, and then every thing disappears.
I tried to print i on the console but even on the console make the results and every thing was gone.
I am sure I did every thing good so what is the solution to make it work here?
The form is being submitted when you click the button.
onload event can be used to set the click event of the button.
Prevent the submit:
<form onsubmit="return false;">
JS:
window.onload = function() {
btn = document.getElementById('btn');
btn.onclick = function() {
start = document.forms[0].start;
end = document.forms[0].end;
result = document.getElementById('result');
selector = document.getElementById('selector');
i = start.value;
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
}
start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
'use strict';
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button type="button" value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
Use type="button" into your button.
as simple example on your code, just add parameter event, and prevent defaults event of form submit, you can also change the type of
<button value="generate" id="btn" type='button'> generate</button>
btn.onclick = (event)=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
event.preventDefault();
}
If you are trying to add a new option to the select use the "appendChild()" function:
var form = document.getElementByTagName("form")[0];
var btn = document.getElementById('btn');
//To avoid refresh the page when the form is submited.
form.addEventListener("click", function(e){e.preventDefault()},false);
btn.onclick = () => {
var result = document.getElementById('selector'),
var option= document.createElement("option");
option.innerHTML = "some text";
result.appendChild(option);
}
This wild add a new option in the select each time you click the add button

jQuery .click() event isn't firing on-click

$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
I'm having an issue getting this snippet to run. form-1 is hidden, backButton-1 is created after the end of form-2 and only after form-1 has been hidden. I want backButton-1 to empty out form-2 and unhide form-1 but the .click event isn't firing.
Here's the code:
$(document).ready(function() {
var playersName = '';
var gameName = '';
var playersNameArray = [];
$("#submit-1").click(function() {
playersName = $("#input_players").val();
gameName = $("#input_game").val();
$("#form-1").hide();
gameName = gameName.toLowerCase();
gameName = gameName.charAt(0).toUpperCase() + gameName.substr(1);
function makeArray(string) {
string = string.replace(/\s/g, '');
var array = string.split(",");
for (let i = 0; i < array.length; i++) {
array[i] = array[i].toLowerCase();
array[i] = array[i].charAt(0).toUpperCase() + array[i].substr(1);
}
playersNameArray = array;
}
makeArray(playersName);
function makeScores(array) {
$("#container-1").prepend("<p>Input " + gameName + " scores:</p>");
for (let i = 0; i < array.length; i++) {
var scoreDiv = document.createElement("div");
scoreDiv.className = "score";
scoreDiv.id = "score-" + (i + 1);
var scoreInput = document.createElement("input");
$(scoreInput).attr('type', 'text');
scoreInput.id = "scoreInput-" + (i + 1);
$("#form-2").append(scoreDiv);
$("#score-" + (i + 1)).append("<div class='scoreName'>" + array[i] + "</div>");
$("#score-" + (i + 1)).append(scoreInput);
}
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
);
}
makeScores(playersNameArray);
});
$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
$("#submit-2").click(function() {
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
You are saying the button is being created, which means that jQuery cannot add an event listener on load. Either create the listener together where you create the button, or use propagation.
// Create button, add to DOM
$("<div>New div</div>").appendTo("body")
.click(function() {
// Attach click event listener
alert("Works!");
});
// Or using propagation
$("body").on("click", "#test", function() {
alert("Works too!");
});
$("<div id='test'>New div</div>").appendTo("body");
Note that the second approach works irrespective of where you attach the event listener to body, be it before or after creating the new item.
In your case, I suggest:
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
).on("click", "#backButton-1", function() {
$("#form-2").empty();
$("#form-1").show();
});
Try adding your links at the bottom
and add the following link in your head
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script> <!-- <<<< This ONE-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input**strong text**_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
<script type="text/javascript" src="main.js"></script>
</body>

how to display different function in a same textbox?

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;

Problems with JavaScript calculator

I'm making this calculator and have no idea why nothing comes into tulos box. Here is the code, I hope someone can help me. I'm starter with these kind of things, so there might be some really big mistakes in code.
<html>
<head>
<title>Laskurit</title>
</head>
<body>
<script language="JavaScript">
<!--
function Laskin() {
var paino = document.korvaus.paino.value;
var hinta = document.korvaus.hinta.value;
var mista = document.korvaus.mista.value;
var tulos;
if (mista == "koti")
{
paino *= 20 == koti1;
if (koti1 >= hinta)
{
tulos = hinta;
}
else
{
tulos = koti1;
}
}
else if (mista == "ulko")
{
paino *= 9,75 == ulko1;
if (ulko1 >= hinta)
{
tulos = hinta;
}
else
{
tulos = ulko1;
}
}
document.korvaus.tulos.value = tulos;
}
-->
</script>
<p><b>Korvauslaskuri</b></p>
<form name="korvaus">
<table><tr><td>Paino: <td><input type="text" name="paino"><br>
<tr><td>Kokonaishinta(€): <td><input type="text" name"hinta"><br>
<tr><td>Mistä/mihin?<br>
<td><select name="mista">
<option value="koti">Kotimaa</option>
<option value="ulko">Ulkomaa</option>
</select>
<tr><td>
<p>Korvausmäärä(€):</p>
<td><p><input type="text" size="40" name="tulos"></p>
</table></form>
<form name="nappulalomake">
<p><input type="button" name="B1" value="Laske" onClick="Laskin()"></p>
</form>
</body>
</html>
Not exactly sure what you are trying to accomplish but there were a few syntax errors in your code. Here working code
<html>
<head>
<title>Laskurit</title>
<script language="JavaScript">
<!--
function Laskin() {
var paino = document.korvaus.paino.value;
var hinta = document.korvaus.hinta.value;
var mista = document.korvaus.mista.value;
var tulos;
if (mista == "koti")
{
var koti1 = paino *20;
if (koti1 >= hinta)
{
tulos = hinta;
}
else
{
tulos = koti1;
}
}
else if (mista == "ulko")
{
var ulko1 = paino *9.75;
if (ulko1 >= hinta)
{
tulos = hinta;
}
else
{
tulos = ulko1;
}
}
document.korvaus.tulos.value = tulos;
}
-->
</script>
</head>
<body>
<p><b>Korvauslaskuri</b></p>
<form name="korvaus">
<table border=0>
<tr><td>Paino: </TD><td><input type="text" name="paino"></td></tr>
<tr><td>Kokonaishinta(€):</tD><td><input type="text" name="hinta"></td></tr>
<tr><td>Mistä/mihin?</td><td><select name="mista">
<option value="koti">Kotimaa</option>
<option value="ulko">Ulkomaa</option>
</select>
</td></tr>
<tr><td>
<p>Korvausmäärä(€):</p></td>
<td><p><input type="text" size="40" name="tulos"></p></td>
</tr>
</table></form>
<form name="nappulalomake">
<p><input type="button" name="B1" value="Laske" onClick="Laskin()"></p>
</form>
</body>
</html>

Categories