I need to make a simple project in javascript, we need to create a single library with javascript objects and let the user to add new books. I requested user data with a form tag in html and created new objects and I stored them inside a single array called library. The books are showed with no problem in the DOM the thing is that I need a button that deletes an specific book, I created a single button but it only deletes the first book in the array. I hope you can help me.
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="stylesheet" href="./styles.css" />
<title>Document</title>
</head>
<body>
<h1>My Library</h1>
<input id="title" type="text" placeholder="Book Title">
<input id="author" type="text" placeholder="Book Author">
<input id="date" type="text" placeholder="Publish Date">
<select id="read" name="read">
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<input type="button" value="New Book" onclick="add_book()">
<div id="display"></div>
<script src="app.js"></script>
</body>
</html>
------------------------------------------------------------------------------------------------
JAVASCRIPT:
var library = [];
var title_input = document.getElementById("title");
var author_input = document.getElementById("author");
var date_input = document.getElementById("date");
var read_input = document.getElementById("read");
function Book(title, author, date, read) {
this.title = title;
this.author = author;
this.date = date
this.read = read
};
function add_book() {
var newBook = new Book(title_input, author_input, date_input, read_input)
library.push(`Title: ${newBook.title.value} <br>`+`Author: ${newBook.author.value} <br>`+
`Realease date: ${newBook.date.value} <br>`+`Readed: ${newBook.read.value} <br>` )
show_library();
};
function delete_book(arr, elem){
index = arr.indexOf(elem);
arr.splice(elem,1);
show_library();
}
function show_library() {
document.getElementById("display").innerHTML = "";
for(i = 0; i<library.length; i++){
document.getElementById("display").innerHTML += library[i]+
'<button onclick="delete_book(library, library[i]);">Delete</button><br>';
}
};
You've written library[i] as plain text into the DOM. This doesn't references the variable i from your loop.
You can simply write the index as argument and use this directly in your function delete_book.
var library = [];
var title_input = document.getElementById("title");
var author_input = document.getElementById("author");
var date_input = document.getElementById("date");
var read_input = document.getElementById("read");
function Book(title, author, date, read) {
this.title = title;
this.author = author;
this.date = date
this.read = read
};
function add_book() {
var newBook = new Book(title_input, author_input, date_input, read_input)
library.push(`Title: ${newBook.title.value} <br>`+`Author: ${newBook.author.value} <br>`+
`Realease date: ${newBook.date.value} <br>`+`Readed: ${newBook.read.value} <br>` )
show_library();
};
function delete_book(arr, index){
arr.splice(index, 1);
show_library();
}
function show_library() {
document.getElementById("display").innerHTML = "";
for(i = 0; i<library.length; i++){
document.getElementById("display").innerHTML += library[i]+
`<button onclick="delete_book(library, ${i});">Delete</button><br>`;
}
};
<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="stylesheet" href="./styles.css" />
<title>Document</title>
</head>
<body>
<h1>My Library</h1>
<input id="title" type="text" placeholder="Book Title">
<input id="author" type="text" placeholder="Book Author">
<input id="date" type="text" placeholder="Publish Date">
<select id="read" name="read">
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<input type="button" value="New Book" onclick="add_book()">
<div id="display"></div>
<script src="app.js"></script>
</body>
</html>
Related
I made a username and password validation but although I filled in valid information, it outputs invalid. The input is from <input> tag, with IDs, where the information entered is stored into arrays. Is it data type or syntax issues?
HTML Code 1:
<!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>Document</title>
</head>
<body>
<span>Username</span>
<input id="user" placeholder="enter username">
<br>
<br>
<span>Password</span>
<input id="pass" placeholder="enter password">
<br>
<br>
<button onclick="save()">Enter</button>
<script src="pass.js"></script>
</body>
</html>
HTML Code 2:
<!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>Document</title>
</head>
<body>
<span>Username</span>
<input id="user" placeholder="enter username">
<br>
<br>
<span>Password</span>
<input id="pass" placeholder="enter password">
<br>
<br>
<button onclick="valid()">Validate</button>
<br>
<br>
<h1 id="ans"></h1>
<script src="pass.js"></script>
</body>
</html>
Javascript Code (in a separate file):
var user = [];
var pass = [];
function save( ) {
var x = document.getElementById("user").value;
var y = document.getElementById("pass").value;
user.push(x);
pass.push(y);
console.log(user);
}
function valid() {
var a = document.getElementById("user").value;
var b = document.getElementById("pass").value;
var validationa;
var validationb;
for (let x in user) {
if (x == a) {
validationa = 1;
} else {
validationa = 0;
}
}
for (let y in pass) {
if (y == b) {
validationb = 1;
} else {
validationb = 0;
}
}
if (validationa == 1 && validationb == 1) {
document.getElementById('ans').innerHTML = "valid";
} else {
document.getElementById('ans').innerHTML = "invalid";
}
}
It gives a valid output if the username and password entered is consistent. Both HTML files use the same Javascript source file.
So I've been trying to get user input to calculate outer product of two vectors using tensorflow.js but I couldn't figure out how to get an array from html to pass it into javascript. for example inside the calculator function const a has to be something like this tf.tensor1d([1, 2, 3])
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1 class="text1">Welcome to vector cross product calculator!</h1>
<h2>Please enter two vectors like 1,2,3 and 3,2,1</h2>
<label>vector a</label>
<input type="text" name="vectora" id="vectora" class="vectora" placeholder="enter a vector like 1,2,3"> <br>
+<br>
<label>vector b</label>
<input type="text" name="vectorb" id="vectorb" class="vectorb" placeholder="enter a vector like 1,2,3"><br>
<button type="button" class="btn btn-info" onclick="calculator()">submit</button><br><br>
<div class="screen" id="screen1"></div>
</button>
<script>
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(vectora);
const b = tf.tensor1d(vectorb);
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
</script>
</body>
</html>
A utility function getArray can help.
function getArray(data) {
return data.split(',').map(s => +s)
}
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(getArray(vectora));
const b = tf.tensor1d(getArray(vectorb));
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1 class="text1">Welcome to vector cross product calculator!</h1>
<h2>Please enter two vectors like 1,2,3 and 3,2,1</h2>
<label>vector a</label>
<input type="text" name="vectora" id="vectora" class="vectora" placeholder="enter a vector like 1,2,3"> <br>
+<br>
<label>vector b</label>
<input type="text" name="vectorb" id="vectorb" class="vectorb" placeholder="enter a vector like 1,2,3"><br>
<button type="button" class="btn btn-info" onclick="calculator()">submit</button><br><br>
<div class="screen" id="screen1"></div>
</button>
<script>
function getArray(data) {
return data.split(',').map(s => +s)
}
function calculator(){
var vectora = document.getElementById("vectora").value;
var vectorb = document.getElementById("vectorb").value;
const a = tf.tensor1d(getArray(vectora));
const b = tf.tensor1d(getArray(vectorb));
var c = tf.outerProduct(a, b);
document.getElementById("screen1").innerHTML=c;
}
</script>
</body>
</html>
I'm making a code where the user enters information and it stores it in an object, but when I check if the object is saved by alerting one of its values it says there is no such object.
here is my code.
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name#gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
Is there some sort of error that I'm not seeing?
After click on submit button in form with action="" page is reload and all data is lost. Pleas use:
<form action="javascript:void(0)">
instead of
<form action="">
This prevent page reload.
I've got a very simple form and I'm want the values to empty when I submit in order to use again without refreshing the page. What I've got isn't working for some reason.
My initial idea was to set the values of the inputs to empty strings on form submit, but when I log them into the console they don't do that. Anyone know what I'm doing wrong here?
<!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>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
let form = document.getElementById("form");
let volume = document.getElementById("volume");
let denied = document.getElementById("denied");
let charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function (e) {
e.preventDefault();
volume = volume.value;
denied = denied.value;
charges = charges.value;
let curDenialRate = parseFloat((denied / volume) * 100);
charges = parseFloat(charges * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(charges);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
volume = " ";
denied = " ";
charges = " ";
return false;
};
Use HTMLFormElement.reset():
let form = document.getElementById("form");
const volume = document.getElementById("volume");
const denied = document.getElementById("denied");
const charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function(e) {
e.preventDefault();
let a = volume.value;
let b = denied.value;
let c = charges.value;
let curDenialRate = parseFloat((b / a) * 100);
c = parseFloat(c * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(c);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
form.reset();
return false;
};
<!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>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
How you are clearing values will not work. You are trying to change the variable but that will not affect the DOM element or its value.
You will have to use the below code with value property to change the value.
document.getElementById("volume").value= " ";
document.getElementById("denied").value= " ";
document.getElementById("charges").value= " ";
I dont understand why the button will not become active after it is enabled with the check box. I have got it to work without disabling the submit button but then it works independent of the checkbox being checked
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-
scalable=0, width=device-width;">
<title>Welcome to Tiffany & Co.</title>
<link rel="stylesheet" href="index.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<!--Enable media queries in some unsupported subrowsers-->
<script type="text/javascript" src="css3-mediaqueries.js"></script>
<script type="text/javascript" src="main.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<script>
function submitAction()
{
var link = document.location.href;
var searchString = "redirect=";
var equalIndex = link.indexOf(searchString);
var redirectUrl = "";
if (document.forms[0].action == "")
{
var url = window.location.href;
var args = new Object();
var query = location.search.substring(1);
var pairs = query.split("&");
for(var i=0;i<pairs.length;i++)
{
var pos = pairs[i].indexOf('=');
if(pos == -1) continue;
var argname = pairs[i].substring(0,pos);
var value = pairs[i].substring(pos+1);
args[argname] = unescape(value);
}
document.forms[0].action = args.switch_url;
}
if(equalIndex >= 0)
{
equalIndex += searchString.length;
redirectUrl = "";
redirectUrl += link.substring(equalIndex);
}
if(redirectUrl.length > 255)
redirectUrl = redirectUrl.substring(0,255);
document.forms[0].redirect_url.value = redirectUrl;
document.forms[0].buttonClicked.value = 4;
document.forms[0].submit();
}
function reject()
{
alert("You will not be able to access the system!");
}
function loadAction() {
var url = window.location.href;
var args = new Object();
var query = location.search.substring(1);
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) continue;
var argname = pairs[i].substring(0, pos);
var value = pairs[i].substring(pos + 1);
args[argname] = unescape(value);
}
document.forms[0].action = args.switch_url;
}
</script>
<form method="post">
<input TYPE="hidden" NAME="buttonClicked" SIZE="16" MAXLENGTH="15" value="0">
<input TYPE="hidden" NAME="redirect_url" SIZE="255" MAXLENGTH="255" VALUE="">
<input TYPE="hidden" NAME="err_flag" SIZE="16" MAXLENGTH="15" value="0">
<h1>Welcome to Tiffany & Co.</h1>
<p id="desc">We're delighted to offer our customers complimentary Wi-Fi
while shopping in our store.</p>
<form>
<p id="terms">
<input id="termsCheckbox" type="checkbox"
onclick="this.form.submit.disabled = !this.checked"/> I have read and agreed to the Terms of Use
</p>
<p id="error">
Please agree to the Terms of Use by checking the box.
</p>
<p class="connect">
<input id="connect" type="button" name="submit" value="Accept"
class="button" disabled="disabled" onclick="submitAction();">
</p>
</form>
<div id="logo">
<img src="logo.png" width="108" height="14" alt="Tiffany & Co."
/>
</div>
</div>
</body>
</html>
Your code works fine, it's a mess, but it works. The issue is this:
Uncaught ReferenceError: submitAction is not defined
The cause of the issue is that you don't have a closing brace on submitAction()
Here's a working demo. I've also cleaned up your code!
Properly formatting and indenting your code is very important. Not only does it look good and makes it easier to read, you will easily spot mismatched/missing braces.
Try with this
$(function(){
$('#termsCheckbox').change(function(){
$('#connect').prop('disabled', !this.checked);
}
});