I'm having trouble figuring out how to do this, and well, need help.
I'm trying to put my information into an array that's going to be shown and always be able to grow. I need help deleting specific entries into it, either by searching for one or by pointing a mouse and deleting it,
Is there any nice easy way to do it?
<!doctype html>
<html lang="sv">
<body>
<head>
<meta charset="UTF-8">
</title>
</head>
<body>
<input type="text" placeholder="Förnamn" id="name" autofocus>
<input type="date" id="pnummer" autofocus>
<input type="text" placeholder="Efternamn" id="enamn" autofocus>
<input type="button" value="mata in" onclick="register()">
<input type="button" value="visa" onclick="show()">
<script type="text/javascript">
array=[]
function register()
{
var fnamn = document.getElementById("name").value;
var enamn = document.getElementById("enamn").value;
var pnummer = document.getElementById("pnummer").value;
var p1 = new Person(fnamn,pnummer,enamn);
array.push(p1);
}
function Person(fnamn, pnummer, enamn)
{
this.fnamn=fnamn;
this.pnummer=pnummer;
this.enamn=enamn;
this.visa=function()
{
var panel ="Förnamn:"+" "+this.fnamn+" "+"Efternamn:"+" "+this.enamn+" "+"Personnummer:"+" "+this.pnummer+"<br>";
return panel;
}
}
function show(){
var showperson=document.getElementById("new");
showperson.innerHTML="";
var i=0;
while (array.length>i)
{
showperson.innerHTML+=array[i].visa()
i++;
}
}
</script>
<p id="new"></p>
<div id="panel"></div>
</body>
</html>
I am not 100% sure what you're trying to do or what some of those words mean but is this what you're trying to do?
var peopleTracker = {};
var peopleCounter = 0;
function addPerson()
{
// get the values
var firstName = document.getElementById("firstName").value.trim();
var lastName = document.getElementById("lastName").value.trim();
var birthday = document.getElementById("birthday").value.trim();
// make sure none are blank
if(firstName == "" || lastName == "" || birthday == "") return;
// give each person an ID so we can remove them later
var personID = ++peopleCounter;
peopleTracker[personID] = {
"firstName" : firstName,
"lastName" : lastName,
"birthday" : birthday
};
// add the person to the table
var row = document.getElementById("peopleList").insertRow();
row.insertCell().innerText = firstName;
row.insertCell().innerText = lastName;
row.insertCell().innerText = birthday;
row.insertCell().innerHTML = 'remove';
}
// delete a user from the tracker and remove the row
function removePerson(row, personID)
{
delete peopleTracker[personID];
row.parentNode.removeChild(row);
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>the dingo ate my baby</title>
</head>
<body>
<input type="text" placeholder="First Name" id="firstName" autofocus>
<input type="text" placeholder="Sur Name" id="lastName" autofocus>
<input type="date" id="birthday" autofocus>
<input type="button" value="Add Person" onclick="addPerson()">
<br /><br />
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Sur Name</th>
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tbody id="peopleList"></tbody>
</table>
</body>
</html>
A few thoughts:
If you're going to use an array to delete then you're going to need to use some unique ID to be able to find the person you want to delete. You cannot use the array index because that will change as you remove people from the array.
By using an object to store the users you can delete by using a unique ID that changes for each user added.
I jQuery is an option, you could find the index of your clicked <div> and delete the element with something like the following function:
$( "div.someIdYouGiveIt" ).click(function() {
var index = $( "div.someClassYouGiveIt" ).index( this );
array.splice(index, 1);
});
Related
So I have this expense tracker website, it's just a beginner JavaScript project. I have an issue with deleting rows. If I click on the delete button it always deletes the first row below the heading, rather than deleting the row which I want to delete.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script
src="https://kit.fontawesome.com/60cb322ae0.js"
crossorigin="anonymous"
></script>
<title>Expense Tracker</title>
</head>
<body>
<div class="wrapper">
<h1>Expense Tracker</h1>
<form action="">
<label for="">Name</label>
<input
class="name"
type="text"
placeholder="Where was the expense made"
/><br />
<label for="">Date</label>
<input class="date" type="date" />
<label for="">Amount</label>
<input class="amount" type="number" /><br />
<button class="btn" type="submit">Add Expense</button>
</form>
</div>
<table>
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th></th>
</tr>
</table>
<script src="index.js"></script>
</body>
</html>
JavaScript Code
const name = document.querySelector(".name");
const date = document.querySelector(".date");
const amount = document.querySelector(".amount");
const btton = document.querySelector(".btn");
const table = document.querySelector("table");
//Event
btton.addEventListener("click", toTable);
table.addEventListener("click", toDelete);
//fucntion
function toTable(event) {
event.preventDefault();
//creating table row
const tableRow = table.insertRow();
//creating table definitions
const tableName = tableRow.insertCell();
const tableDate = tableRow.insertCell();
const tableAmount = tableRow.insertCell();
const tableDelete = tableRow.insertCell();
tableDelete.classList.add("trash");
//assigning values
tableName.innerHTML = name.value;
tableDate.innerHTML = date.value;
tableAmount.innerHTML = amount.value;
tableDelete.innerHTML = "<i class='far fa-trash-alt'></i>";
//making the input fields clear
name.value = "";
date.value = "";
amount.value = "";
}
function toDelete(event) {
var item = document.querySelector(".trash");
item = item.parentElement;
item.remove();
}
Sorry for this mess of a code, I just started coding.
When you do document.querySelector(".trash") it will fetch the first element on the page with a trash class. That is why the first row gets deleted.
What you should probably do is search for the parentElements class from the event you are getting.
Something like this:
function toDelete(event) {
let row=event.target.closest(".parents-class");
row.remove();
}
event.target will give you a reference to the object on which the event was dispatched. In your case this is probably the element that was clicked. From there we try to move up the DOM to the parent that we want to delete and then remove it.
Alternatively you could search for the closest tr tag and directly delete it that way:
function toDelete(event) {
let row=event.target.closest("tr");
row.remove();
}
Hi guys im a grade 10 student and was asked to create a basic like calculator to solve for the area of the triangle, but i really dont know how.I can do it with the use of a radio button but my teacher said to do it without the radio input. My codes works fine but if i press clear and input a value to the base and height, it will say syntax error...please can you help me? also whenever i dont put a value on base and height,it says 0 instead of syntax error,so please help me....(also sorry about earlier, im just new to this site)
this is my code:
<html>
<head>
<title>hfsabfhsabfihs</title>
</head>
<body>
<script type="text/javascript">
<!--
function checkbutton() {
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
if (document.form1.checked == false) {
alert("Syntax Error")
} else {
alert(num1 * num2 / 2);
}
}
function clearbutton() {
document.form1.checked = false;
var num1 = document.getElementById("input1").value = "";
var num2 = document.getElementById("input2").value = "";
}
//-->
</script>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" value="Compute" onclick="checkbutton()">
<input type="button" value="Clear" onclick="clearbutton()">
</body>
</html>
problem is on clear function function
function clearbutton()
{
// document.form1.checked= false;
var num1 = document.getElementById("input1").value="";
var num2 = document.getElementById("input2").value="";
}
you are getting this error because you have set a variable here i.e form1.checked. either remove this variable or change its value on calculation function
Hope the below code helps:
// vairbale
const baseInput = document.querySelector("#input1")
const heightInput = document.querySelector("#input2")
const coputeBTn = document.querySelector("#Compute")
const areaTriangle = (base, height) =>{
let total =""
let error = false
let errorMessage = ""
if(base != "" && height != ""){
error = false
total = base * height / 2
}else{
error = true
errorMessage = "Please fill all inputs."
return errorMessage
}
return total
}
// Calling Function
coputeBTn.addEventListener("click", ()=>{
console.log(areaTriangle(Number(baseInput.value), Number(heightInput.value)))
})
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" id="Compute" value="Compute">
<input type="button" value="Clear" onclick="clearbutton()">
</form>
</body>
</html>
Currently working on an "retirement calculator" where I have to generate a table for money-saved each year based on data entered into the first two forms. Unfortunately I can't figure out why it's not appending the table to the site. I don't receive any errors on the console.
I'm also a complete novice at JS/JQ. The code for calculate is near the bottom. I realize it may look at little all over the place, I'm trying to get it to work first before I got back and clean it up some.
EDIT: I took out some methods so there isn't so much to traverse. Assume that the variables involved in calculate are set to real values (aka they're not null/NaN).For example there's an add JQuery method that'll add more scenarios. But since it distracts from the problem I took it out. But the for loop runs in relation to the array
var scenarioCount=0;
var hasError=false
var error=false;
var YOB;
var CurrSav;
var RetAge;
var LifeExp;
var Year;
var scenarios = new Array();
$(document).ready(function ()
{
$('#calculate').on('click', function(e)
{
if(!isBasicInfoValid()) //check to see if basic info is correct
{
if(!error) //if there isn't already an error put one
{
$('#basic').append($("<div class='basicError'>Input is not valid! </div>"));
}
resetVars(); //reset the variables
error=true; //say there is an error on screen
}
else
{
$("#basic .basicError").remove();
error=false;
calculate();
}
e.preventDefault();
});
});
function calculate()
{
var body = document.getElementById('body');
//body is null right here for some reason
$(body).append("<div id='results' class='form'>");
for(var i=0;i<scenarios.length;i++)
{
var element = scenarios[i];
var n = parseInt(YOB)+parseInt(RetAge)-Year;
var m = LifeExp-RetAge;
var r = 1+element.workRate;
var g = 1 + element.retiredRate;
var I = CurrSav;
var T = element.retIncome;
var part1 = (T/Math.pow(g,m-1))*((1-Math.pow(g,m))/(1-g))-(I*Math.pow(r,n));
var S = part1*(1-r)/(1-Math.pow(r,n));
var savings=I;
$('#results').append("<div><h4>You need to save "+S+" dollars</h4></div>")
$('#results').append("<table id=t><tr><th>Year</th><th>Money Saved</th></tr>");
for(var j=n;j>0;j--)
{
savings=S+savings*r;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
for(var j=m;j>0;j--)
{
savings=(savings-T)*g;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
$('#results').append("</table></div>");
}
};
function resetVars()
{
YOB=null;
CurrSav=null;
RetAge=null;
LifeExp=null;
Year=null;
}
function scenarioObject()
{
var obj={
nameScen : document.forms["scenario"]["ScenarioName"].value,
workRate : document.forms["scenario"]["Working"].value,
retiredRate : document.forms["scenario"]["Retired"].value,
retIncome : document.forms["scenario"]["desiredInc"].value
}
return obj;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3</title>
<link rel='stylesheet' type='text/css' href='/uncSemester7/comp426/a3/assignment3.css'>
<script src='/uncSemester7/comp426/a3/jquery-1.10.2.js'></script>
<script src='/uncSemester7/comp426/a3/assignment3.js'></script>
</head>
<body>
<div class='form'>
<h3> Basic Information </h3>
<form id='basic'>
<div>Year of Birth: <input type='number' name='YOB'> </div>
<div>Current Savings: <input type='number' name='CurrSav'>
</div>
<div>Expected Retirement Age: <input type='number' name='RetAge'></div>
<div>Life expectancy: <input type='number' name='LifeExp'>
</div>
</form>
</div>
<div id='scenDiv' class='form'>
<div id='buttons'>
<div><button id='add' type='submit'>Add Scenario </button></div>
<div><button id='calculate' type='submit'> Calculate </button></div>
</div>
<h3> Scenario </h3>
<form id='scenario'>
<div>Name: <input type='text' name='ScenarioName'> </div>
<div>Rate of Investment Return (While Working): <input type='number' name='Working'></div>
<div>Rate of Investment Return (Retired): <input type='number' name='Retired'></div>
<div>Desired Retirement Yearly Income: <input type='number' name='desiredInc'></div>
</form>
</div>
</body>
</html>
You're using getElementById('body'), where you should be using getElementsByTagName('body')[0], as body is not an id, but a tag. Or better yet with jQuery since you're already using it, $('body').
I'm making a recipe calculator for my coursework. I have reached the stage where it will correctly validate everything and make a new row in a table. Sadly in the if statement within the recipe function, it always goes true for isNaN? No matter what I put? Can anyone help me with this?
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<script type="text/javascript">
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var ingredientcount = 0
// The save function
function save(){
var verified = true;
while(verified){
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if(serves === "" || name === "" || isNaN(serves)=== true)
{
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
}
else{
alert("sucess!");
// array(ingredient,amount,unit,name,serves)
return;
}
}
}
// The function to valiate the data and manage everything
function recipe(){
if(ingredient === ""|| amount === "" || unit === "Select Unit"){
alert("You must fill in all fields.")
}
else if(isNaN(amount)){
alert("You have to enter a number in the amount field")
}
else{
alert("hey!")
alert(recipe[1][2] + recipe[1][1])
var totalamount = amount + " "+ unit
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
ingredientcount ++;
alert(ingredientcount);
}
}
</script>
</head>
<body>
<h1>Recipe Name</h1>
<h2>Serves many people </h2>
<table border="1" id="table" >
<tr>
<td>
<input type="text" id="ingredient" placeholder="Enter an Ingredient">
</td>
<td>
<input type="text" id="number" placeholder="Enter an amount">
<select id="unit">
<option>Select Unit</option>
<option>Grams</option>
<option>Mililitres</option>
<option>Number</option>
</select>
</td>
<td>
<button type="button" onclick="recipe()">Add</button>
<button type="button" onclick="save()">Save</button>
</td>
</tr>
<th>Ingredient</th>
<th>Amount</th>
<th> </th>
</table>
</body>
</html>
The problem is that you are setting the values of ingredient, amount, and unit when the page loads, not when the Add button is pushed. You need to move those assignments to the recipe() function.
I need to add product info from inputs to table by using jQuery library. I am trying for quite some time now, but I don't get anywhere. First I need to enter data to inputs, select appropriate radio button and than validate input fields. If there are no errors, product info should be added to table. I tried with the following code: jsFiddle
Nothing works as intended tho. What am I doing wrong?
JS code:
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function () {
//Check if any of requested inputs is empty
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").val('Missing product name');
break;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").val('Missing price');
break;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
//Check radio buttons and assign values
if ($('input[value = "true"]'.is(':checked')) {
onStack = "Product available";
} else if ('input[value = "false"]'.is(':checked') {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>$productName</td><td>$price</td><td>$onStack</td></tr>");
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<body>
<form method="" action="">
<input type="text" id="name" placeholder="Product name" />
<br />
<input type="text" id="price" placeholder="Price" />
<br/>
<input type="radio" name="stack" value="true">Product available
<br />
<input type="radio" name="stack" value="false">Product not available
<br />
<input type="submit" value="Submit">
</form>
<div id="errors"></div>
<br />
<table border="1">
<tr>
<th>Product name</th>
<th>Price</th>
<th>Stack</th>
</tr>
</table>
<div id="sumOnStack">Sum of available products</div>
<div id="SumNotOnStack">Sum of unavailable products</div>
<input type="button" id="resetForm" value="Reset form" />
<br />
</body>
</html>
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function ( e) {
//Check if any of requested inputs is empty
$("#errors").html('');
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").html('Missing product name');
return false;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").html('Missing price');
return false;
} else if($('input[name="stack"]:checked').length == 0) {
$("#errors").html('Missing product availibility');
return false;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
var stack = $('input[name="stack"]:checked');
console.log( $(stack).val() );
//Check radio buttons and assign values
if ($(stack).val() == 'true') {
onStack = "Product available";
} else {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>"+productName+"</td><td>"+ price +"</td><td>"+ onStack +"</td></tr>");
return false;
});
});
Please try this. Hope above code will help u.