eval() function not working in the calculator project - javascript

I am trying to finish a calculator project. I have successfully designed the HTML and CSS of the calculator, but facing issues in my JavaScript code. The ERROR coming is:
Uncaught SyntaxError: Invalid left-hand side in assignment
at HTMLButtonElement.addOutput (logic.js:13)
How to sort out the problem? Can anybody help on this?
I have added the complete project code. But the error is mainly in javascript.
The code:
JAVASCRIPT
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
console.log(e.target.innerText);
let char = e.target.innerText;
msg =screen.value += char
if( char=='C'){
screen.value=" ";
}
else if(char=='=')
{
screen.value = eval(msg)
}
else{
msg="";
}
}
for (item of buttons){
item.addEventListener('click', addOutput);
}
HTML:
<!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>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="screen_style">
<h1>Calculator</h1>
</div>
<div class="calculator">
<input type="text" name="screen" id="screen">
<table>
<tr>
<td><button>(</button></td>
<td><button>)</button></td>
<td><button>C</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>x</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
</div>
</body>
<script src="logic.js"></script>
</html>
CSS:
.screen_style{
background-color: rgb(135, 222, 208);
width: 31%;
border: 1px solid white;
margin: auto;
border-radius: 20px;
}
.container{
text-align: center;
}
table{
margin: auto;
}
input{
font-size: 34px;
border: 4px solid brown;
border-radius: 21px;
margin: auto;
}
button{
font-size: 23px;
width: 90px;
height: 75px;
border-radius: 20px;
}
button:hover{
background-color: rgb(109, 128, 0);
}
.calculator{
background-color: khaki;
display: inline-block;
border-radius: 21px;
padding: 23px;
}

You are using += which is Addition Assignment. So this line,
msg = screen.value += char
means
msg = screen.value = screen.value + char
Which is invalid.
You need to just use a + to concatenate the char to screen.value.
UPDATE
You were adding a = at the end of screen.value which caused eval to throw error. You need to check if the char is a = before concatenating it to screen.value.
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
let char = e.target.innerText;
screen.value += ["=", "C"].includes(char) ? "": char
msg = screen.value
if (char == 'C') {
screen.value = " ";
} else if (char == '=') {
screen.value = eval(msg)
} else {
msg = "";
}
}
for (item of buttons) {
item.addEventListener('click', addOutput);
}
.screen_style {
background-color: rgb(135, 222, 208);
width: 31%;
border: 1px solid white;
margin: auto;
border-radius: 20px;
}
.container {
text-align: center;
}
table {
margin: auto;
}
input {
font-size: 34px;
border: 4px solid brown;
border-radius: 21px;
margin: auto;
}
button {
font-size: 23px;
width: 90px;
height: 75px;
border-radius: 20px;
}
button:hover {
background-color: rgb(109, 128, 0);
}
.calculator {
background-color: khaki;
display: inline-block;
border-radius: 21px;
padding: 23px;
}
<!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>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="screen_style">
<h1>Calculator</h1>
</div>
<div class="calculator">
<input type="text" name="screen" id="screen">
<table>
<tr>
<td><button>(</button></td>
<td><button>)</button></td>
<td><button>C</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>x</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
</div>
</body>
<script src="logic.js"></script>
</html>

msg =screen.value += char
I believe you are trying to add char to screen.value, in which case the += should just be +
EDIT: You are adding the char to screen.value before the eval function is called (i.e. eval is getting "5+3=" instead of "5+5".
Updated JavaScript
let screen = document.getElementById('screen');
let buttons = document.querySelectorAll('button');
function addOutput(e) {
console.log(e.target.innerText);
let char = e.target.innerText;
console.log(screen.value)
if( char=='C'){
screen.value=" ";
}
else if(char=='=')
{
screen.value = eval(screen.value)
}
else{
screen.value += char
}
}
for (item of buttons){
item.addEventListener('click', addOutput);
}

Related

my innerHTML doesn't changes when i press the key

I wrote this code where the list item to be added stay in the top of the list, and the order should actualize the just like the variable, but it doens't change, it remains 1
window.addEventListener('keydown', addItem)
var order = 1;
var listItem = [""];
var listQuantity = [0];
var orderin = document.getElementById('order-register');
orderin.innerHTML = order;
function addItem() {
let itemout, qttout, addrow;
let table = document.getElementById('tabelaitens');
let itemin = document.getElementById('itemin');
let qttin = document.getElementById('qttin');
let key = event.key;
if (key == "Enter") {
if (itemin.value != "") {
itemout = itemin.value;
} else {
//add dropdown
}
if (qttin.value > 0) {
qttout = qttin.value;
} else {
//add dropdown
}
if ((itemout != undefined) && (qttout != undefined)) {
orderin.innerHTML = '' + order;
addrow = "<td class=\"order\">" + order + "</td><td class=\"item\">" + itemout + "</td><td class=\"quantity\">" + qttout + "</td>";
table.innerHTML += addrow;
order++;
orderin.innerHTML = order;
}
}
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
table,
tr,
td {
border-collapse: collapse;
}
#tabelaitens {
background-color: blanchedalmond;
width: 1000px;
margin: auto;
}
.linha,
.linharegister {
border-collapse: collapse;
}
.order {
width: 5%;
padding: 10px;
text-align: center;
}
.item {
width: 85%;
padding: 10px 5px;
}
.quantity {
width: 10%;
padding: 10px 5px;
}
#order-register {
text-align: center;
}
#order-register,
.item-register,
.quantity-register {
padding: 5px
}
.item-register>input,
.item-register>input:focus,
.quantity-register>input,
.quantity-register>input:focus {
width: 100%;
background-color: transparent;
border: none;
outline: none;
border-bottom: solid rgb(196, 183, 164);
}
.quantity-register>input {
text-align: center;
}
<!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>Lista de Compras</title>
<link rel="icon" href="img/list.png">
<link rel="stylesheet" href="styletable.css">
<script src="javascript/addlist.js" defer></script>
</head>
<body>
<main>
<ul>
<h1>
<li id="listname">lista</li>
</h1>
</ul>
<table id="tabelaitens">
<tr class="linha">
<td class="order">Ordem</td>
<td class="item">Item</td>
<td class="quantity">Quantidade</td>
</tr>
<tr class="linharegister">
<form>
<td id="order-register">PH</td>
<td class="item-register"><input id="itemin" type="text" name="itemregister" autocomplete="off"></td>
<td class="quantity-register"><input id="qttin" type="number" name="itemregister" autocomplete="off" min="1"></td>
</form>
</tr>
</table>
</main>
</body>
I tried make the var turn into a let, put the value in innerHTML outside the if, and a lot of small things that didn't changed anything at all. I dont know if it is an error in the syntax, logic or whatever, but one thing is right, there is no ";" missing.
You're creating invalid HTML because you don't have <tr> around the new row that you're adding. The browser is trying to fix it, but it ends up putting the added row at the beginning instead of the end. Add this and you get the desired result.
window.addEventListener('keydown', addItem)
var order = 1;
var listItem = [""];
var listQuantity = [0];
var orderin = document.getElementById('order-register');
orderin.innerHTML = order;
function addItem() {
let itemout, qttout, addrow;
let table = document.getElementById('tabelaitens');
let itemin = document.getElementById('itemin');
let qttin = document.getElementById('qttin');
let key = event.key;
if (key == "Enter") {
if (itemin.value != "") {
itemout = itemin.value;
} else {
//add dropdown
}
if (qttin.value > 0) {
qttout = qttin.value;
} else {
//add dropdown
}
if ((itemout != undefined) && (qttout != undefined)) {
addrow = "<tr><td class=\"order\">" + order + "</td><td class=\"item\">" + itemout + "</td><td class=\"quantity\">" + qttout + "</td><tr>";
table.innerHTML += addrow;
order++;
orderin.innerHTML = order;
}
}
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
table,
tr,
td {
border-collapse: collapse;
}
#tabelaitens {
background-color: blanchedalmond;
width: 1000px;
margin: auto;
}
.linha,
.linharegister {
border-collapse: collapse;
}
.order {
width: 5%;
padding: 10px;
text-align: center;
}
.item {
width: 85%;
padding: 10px 5px;
}
.quantity {
width: 10%;
padding: 10px 5px;
}
#order-register {
text-align: center;
}
#order-register,
.item-register,
.quantity-register {
padding: 5px
}
.item-register>input,
.item-register>input:focus,
.quantity-register>input,
.quantity-register>input:focus {
width: 100%;
background-color: transparent;
border: none;
outline: none;
border-bottom: solid rgb(196, 183, 164);
}
.quantity-register>input {
text-align: center;
}
<!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>Lista de Compras</title>
<link rel="icon" href="img/list.png">
<link rel="stylesheet" href="styletable.css">
<script src="javascript/addlist.js" defer></script>
</head>
<body>
<main>
<ul>
<h1>
<li id="listname">lista</li>
</h1>
</ul>
<table id="tabelaitens">
<tr class="linha">
<td class="order">Ordem</td>
<td class="item">Item</td>
<td class="quantity">Quantidade</td>
</tr>
<tr class="linharegister">
<form>
<td id="order-register">PH</td>
<td class="item-register"><input id="itemin" type="text" name="itemregister" autocomplete="off"></td>
<td class="quantity-register"><input id="qttin" type="number" name="itemregister" autocomplete="off" min="1"></td>
</form>
</tr>
</table>
</main>
</body>

Separate Functions For Finding The Area and Perimeter of a Rectangle Part II

So, thanks to a fantastic person here Barmar, I completed my code correctly with user input instead of how I made it initially, which was giving the answer of Area and Perimeter at the same time.
But I am being told to separate this into two functions. Essentially, create separate tasks for the Area and Perimeter calculations and pass the length and width parameters.
It works flawlessly and I am just unsure how to separate this wonderful function into several more...
Below is my codepen and code for it if anyone has any suggestions.
With the help of Barmar, I thought I had done a great job with this, but now I am being challenged one last time before midnight to make separate functions from them. Any advice or pointers would be helpful. Thank you.
CodePen Link
Code Snippet:
function controller() {
var type = document.getElementById("apBox").value;
var length = document.getElementById("lengthBox").value;
var width = document.getElementById("widthBox").value;
var mainSolution = document.getElementById("message");
var answer;
var label;
if (type == "a" || type == "A") {
answer = length * width;
label = 'Area';
} else if (type == "p" || type == "P") {
answer = 2 * length + 2 * width;
label = 'Perimiter';
} else {
mainSolution.innerText = "Invalid. Must Enter 'A' or 'P'";
return;
}
if (length.length > 0 && width.length > 0) {
if (!isNaN(answer)) {
mainSolution.innerHTML = `${label} =&nbsp ${answer}`;
}
} else {
mainSolution.innerHTML = "";
}
}
function clearText() {
document.getElementById("message").innerHTML = ("<br>");
document.getElementById("apBox").value = "";
document.getElementById("lengthBox").value = "";
document.getElementById("widthBox").value = "";
}
#main {
background-color: #455A6F;
border-radius: 3px;
padding: 10px;
}
#header {
background-color: #292A2B;
border-radius: 3px;
padding: 10px;
}
body {
text-align: center;
font-family: Montserrat;
color: #fff;
}
a {
color: rgb(27, 157, 218);
}
.btn1,
.btn2 {
background-color: rgba(52, 139, 221, 0.699);
border: #303436;
font-family: Montserrat;
font-size: 12px;
color: #fff;
letter-spacing: 2px;
padding: 5px;
font-size: 16px;
font-weight: bold;
border-radius: 5px;
line-height: 3;
text-decoration: none;
box-shadow: 0 0 4px black;
text-shadow: 0 1px 0 black;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 1em;
margin-right: 1em;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-shadow: 1px;
text-transform: capitalize;
text-align: center;
}
/* This is a custom snippet I made, so the footer always stays at the bottom of the page */
footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 2em;
background-color: transparent;
text-align: center;
border-color: rgb(0, 0, 0);
border-radius: 18px;
padding: 12px;
margin-top: 30em;
margin-bottom: 1em;
}
.description {
font-style: italic;
}
form {
border-radius: 25px;
padding: 5px;
}
<!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">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="styles.css">
<meta name="description" content="Program 9 Assignment, IS30A, Area of a Rectangle">
<title>Program 9</title>
</head>
<!-- HTML Body -->
<body>
<div id="main">
<div id="header">
<h1>Program 9</h1>
<h5>Area or Perimeter</h5>
<h6>of a Rectangle</h6>
</div>
<!-- Main Form & Inputs For User Interaction -->
<form id="myForm">
<form id="myForm">
<label for="userInput1">Enter A for Area or P for Perimeter:</label><br><br>
<input type="text" id="apBox">
<br><br>
<label for="userInput2">Length:</label><br><br>
<input type="text" id="lengthBox"><br><br>
<label for="userInput3">Width:</label><br><br>
<input type="text" id="widthBox">
</form>
<!-- Empty Field & Message For User Who Interacted as well as Output: -->
<p id="demo">Output: </p>
<p id="message"> <br> </p>
<!-- Buttons For Submit & Clear Fields Above -->
<button class="btn1" type="button" onClick="controller()">Submit</button>
<button class="btn2" type="button" onClick="clearText()">Clear</button>
</div>
<script type="text/javascript" src="controller.js"></script>
</body>
<!-- End HTML -->
</html>
it's actually quite simple to make these their own functions. Your javascript will look like this:
function controller() {
var type = document.getElementById("apBox").value;
var length = document.getElementById("lengthBox").value;
var width = document.getElementById("widthBox").value;
var mainSolution = document.getElementById("message");
var answer;
var label;
if (type == "a" || type == "A") {
answer = Area(length, width);
label = 'Area';
} else if (type == "p" || type == "P") {
answer = Perimiter(length, width);
label = 'Perimiter';
} else {
mainSolution.innerText = "Invalid. Must Enter 'A' or 'P'";
return;
}
if (length.length > 0 && width.length > 0) {
if (!isNaN(answer)) {
mainSolution.innerHTML = `${label} =&nbsp ${answer}`;
}
} else {
mainSolution.innerHTML = "";
}
}
function Perimiter(length, width){
return length * 2 + width * 2
}
function Area(length, width){
return length * width
}
function clearText() {
document.getElementById("message").innerHTML = ("<br>");
document.getElementById("apBox").value = "";
document.getElementById("lengthBox").value = "";
document.getElementById("widthBox").value = "";
}

Javascript form validation not working in the browser properly

I am building a application using pure javascript approach that validates a registration form. The form has five controls: username, password and retype password fields, a checkbox that allows the user to toggle the password visibility and submit button.
I am having some issues trying to understand why my code is not working properly on the browse.
The error messages are not showing.
The button submit is not sending to the confirmation page " I've
tried constantly to solve it but no result".
The check password match is not working.
I hope I explained well.
Many thanks.
Here is the second HTML page for the form submission.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section>
<p>Form Successfully Submitted</p>
</section>
</body>
</html>
Here is my javascript code CSS AND HTML.
function handleInvalidities(input) { // Takes input field as parameter
let errMsg = "";
if (!input.validity.paternMismatch) { // Check for wrong format
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (input.validity.valueMissing) {
errMsg = "Invalid entry. This field can not be blank. Please enter a value."; // Check for missing fields
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none"; // Clear up existing error messages
}
}
function Toggle() {
var temp = document.getElementById("password");
if (temp.type === "password") {
temp.type = "text";
} else {
temp.type = "password";
}
}
function checkPasswordMatch (registerForm) {
let originalPassword = registerForm.password.value;
let retypedPassword = registerForm.retypedpassword.value;
if (originalPassword === retypedPassword) {
return true;
} else {
let passwordMatchError = document.getElementById("passwordmatcherror");
passwordMatchError.setAttribute("class", "error");
passwordMatchError.innerHTML = ("Passwords do not match. Please retype");
return false;
}
}
window.onload = () => {
let registerForm = document.getElementById("regsiterdetails"); // Get the form and add event listener to it
registerForm.addEventListener("submit",
(event) => {
if (!checkPasswordMatch(registerForm)) {
event.preventDefault(); // If no match stop form submitting
}
}, false);
}
body {
font-family: Verdana;
font-size: 0.75rem;
}
h1 {
font-size: 1.25rem;
}
h2 {
font-size: 1rem;
}
label {
display: block;
font-weight: bold;
margin: 0.25rem 0 0.25rem 0;
}
#showpasswordslabel {
display:inline;
}
#showpasswords {
width: 18px;
height: 18px;
}
.error {
width:15%;
min-width: 240px;
display: block;
padding: 0.5rem;
font-size: 0.75rem;
color: white;
background-color: #900;
margin: 0.5rem;
border: 2px solid transparent;
}
input:not(#showpasswords) {
width:15%;
min-width: 240px;
height: 10px;
padding: 10px 0 10px 10px;
margin: 0.5rem;
border: 2px solid transparent;
border-radius: 5px;
box-shadow: 2px 2px 2px #B2B2B2, -1px -1px 1px #292929;
position: relative;
}
button {
margin-top: 1rem;
border: none;
background: #3498db;
width: 80px;
height: 35px;
padding: 0;
margin-top: 16px;
cursor: pointer;
box-shadow: 1px 1px 1px #292929, -1px -1px 1px #B2B2B2;
border-radius: 5px;
transition: all .3s;
color: white;
font-weight: 700;
margin-left: 0.5rem;
}
button:hover {
background: #2980b9;
}
button:focus {
box-shadow: 1px 1px 1px #B2B2B2, -1px -1px 1px #292929;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html" onsubmit="validateForm(event)"></form>
<div>
<label for="username">* Username:</label>
<input type="text" id="username" required>
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one
numeric):</label>
<input type="password" id="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$" required>
<input type="checkbox" id="showpasswords" onclick="Toggle()">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
</body>
<script src="scripts/fma_t3.js"></script>
</html>

js row length needs to reset after row removal

He, i'm almost done with my project but i still have one problem.
when i am removing a table row dynamically, the row count is going terrible wrong. i thought i had the solution for this problem.
how should i reset the row count for the rows after a row remove.
can some one explain what i am doing wrong ?
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
// rework the row length
for (var i = 0; i < row.length; i++) {
rows[i].cells[0].innerText = row.length;
}
console.log(row.length, " 'row lenght' ");
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
Bellow Snippet will give you the answer. However there is a small error on this row remove function. The user must know row index is starting at 0 to get the 1st row. Otherwise a wrong row will be deleted.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
this is my solution i don't think it is the nicest way but it works, thanks for the help with thinking Inuka.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>

Any error in my JQuery code? The lottory can only move one step after click start

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lottery</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.container{
position: absolute;
top: 0;
left:0;
width: 100%;
height: 100%;
background: #333;
}
.nine{
position: relative;
margin: 20px auto;
height: 300px;
width: 300px;
}
.items{
background: #eee;
border-radius: 50px;
width: 80px;
height: 80px;
text-align: center;
}
.active{
background-color: red;
color: #fff;
box-shadow: 0 0 16px rgba(33,154,219,.8), 0 1px 2px rgba(0,0,0,.2) ;
}
.btn-start{
background-color: #3385ff;
cursor: pointer;
color: #fff
}
</style>
</head>
<body>
<div class="container">
<table class="nine">
<tbody>
<tr>
<td class="items" data-index="1">1</td>
<td class="items" data-index="2">2</td>
<td class="items" data-index="3">3</td>
</tr>
<tr>
<td class="items active" data-index="8">8</td>
<td class="items btn-start" data-index="9">start</td>
<td class="items" data-index="4">4</td>
</tr>
<tr>
<td class="items" data-index="7">7</td>
<td class="items" data-index="6">6</td>
<td class="items" data-index="5">5</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="../js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
var gRunning = false;
$(".btn-start").click(function(e){
if(gRunning){
return;
}
gRunning = true;
next(parseInt(Math.random()*50));
});
function next(time){
var activeItem = $(".items.active"),
activeIndex = activeItem.data("index"),
max = $(".items").length -1,
nextTime = time + 5* time/50,
nextIndex = 1,
nextItem = null;
if (activeIndex = max) {
nextIndex = 1;
}
else{
nextIndex = activeIndex + 1;
}
activeItem.removeClass("active");
nextItem = $(".items[data-index="+nextIndex+"]").addClass("active");
if (time>800) {
gRunning = false;
var info = nextItem.text();
alert("Congrats, you got "+ info);
}
else{
window.setTimeout(function(){
next(nextTime);
},nextTime);
}
}
</script>
</body>
</html>
This code stop at data-index:1 after I click the "start" button,then after a while, the alert box will pop up,"congrants, you got 1". any error in the code cause it didn't move forward??? It should be roll several circles then slow down then stop and pop out the alert box.
if (activeIndex = max) {
This is setting activeIndex to max every time, so nextIndex will always be 1.
Use
if (activeIndex == max) {
This is assignment, not comparison:
if (activeIndex = max)
Use ==
if (activeIndex == max)

Categories

Resources