Login interface with javascript [duplicate] - javascript

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 2 years ago.
I am trying to create a working login interface with javascript. I've put down my code but it won't work and it does not show any type of error messages.
Thanks
Taris
function loginFunction() {
var x = document.getElementById("myText");
var y = document.getElementById("myText1");
console.log(x);
console.log(y);
if (x == "Tom" && y == "Halo") {
window.open("www.youtube.de");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>

You need to access the .value of the elements x and y - you're dealing with the element, not the value:
if (x.value == "Tom" && y.value == "Halo") { ... }

You forgot to add .value to selected text field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
<script>
function loginFunction () {
var x = document.getElementById("myText").value;
var y = document.getElementById("myText1").value;
console.log(x);
console.log(y);
if(x === "Tom" && y === "Halo") {
console.log("login in");
//window.open("www.youtube.de");
}
else
{
console.log("failed");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
</script>
</body>
</html>

The problem is that you are reading the value of those input elements. You have assigned the input itself to the variable.
var x = document.getElementById("myText").value;
function loginFunction() {
var x = document.getElementById("myText").value;
var y = document.getElementById("myText1").value;
console.log(x);
console.log(y);
if (x === "Tom" && y === "Halo") {
alert('open page')
//window.open("https://youtube.de");
}
}
const button = document.getElementById("button");
button.addEventListener('click', () => {
loginFunction();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="username" id="myText" value="Tom">
<input type="password" id="myText1" value="Halo">
<button id="button">login</button>
</body>
</html>

Related

Trying to add together multiple inputs in the same input field to get total value

tried cutting the code down as much as possible.
Issue: I'm trying to get the total price of new array objects that are being created from inputs by the user, i tried making a new function that grabs the input, but it changes to the new value in the input field whenever a new item is added. Price also wont change when the user deletes an object from the array.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
//Functions for user input for item name and price
function additemmore () {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if(document.getElementById("item-name-more").value.length == 0)
{
alert("Need a name")
return false;
}
if(document.getElementById("item-price-more").value.length == 0)
{
alert("Need a price")
return false;
}
if(document.getElementById("item-price-more").value === 0)
{
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore(){
itemListmore.innerHTML ="";
for(let i = 0; i < itemArrayMore.length; i++){
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
var total = +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input
type="text"
id="item-name-more"
placeholder="Item name"
/>
<!--for some reason you can add the letter e in the input for price-->
<input
type="number"
id="item-price-more"
placeholder="Write name of item!"
/>
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Make total a global variable. Then you can add to it when you add a new item, and subtract from it when you delete an item.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
var total = 0;
//Functions for user input for item name and price
function additemmore() {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if (document.getElementById("item-name-more").value.length == 0) {
alert("Need a name")
return false;
}
if (document.getElementById("item-price-more").value.length == 0) {
alert("Need a price")
return false;
}
if (document.getElementById("item-price-more").value === 0) {
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore() {
itemListmore.innerHTML = "";
for (let i = 0; i < itemArrayMore.length; i++) {
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
total -= +itemArrayMore[i].price.replace('kr', '');
document.getElementById("total-price").innerHTML = total;
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
total += +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input type="text" id="item-name-more" placeholder="Item name" />
<!--for some reason you can add the letter e in the input for price-->
<input type="number" id="item-price-more" placeholder="Write name of item!" />
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>

How to insert hypen exactly after 3 & 2 places after respectively in a string?

I am creating like a template which accepts user input and hide it with *. I just need to insert hyphens in between like a SSN number. I am almost done just the places are not proper.
<!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>Vue</title>
</head>
<body>
<div id="app">
<input type="text" #input="onInput" v-model="someData" maxlength="11" />
</div>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js"></script>
<script>
Vue.filter("uppercase", function (value) {
const ssnValue = value.substr(0,3) + '-' + value.substr(3, 6) + '-' + value.substr(6);
console.log('fil',ssnValue)
return ssnValue.replace(/\d/g, '*')
});
const app = new Vue({
el: "#app",
data() {
return {
someData: "",
maskedData: "",
};
},
computed: {
getMaskedData() {
return this.maskedData;
},
},
methods: {
onInput(e) {
let originalString = e.data
if(!!originalString)
this.maskedData += originalString;
console.log('mask', this.getMaskedData)
this.someData = this.$options.filters.uppercase(e.target.value);
},
},
});
</script>
</body>
</html>
I referred Insert hyphens in javascript and put dash after every n character during input from keyboard but i am unclear how can i implement those in my case.
When user is entering 123456789, I want like ***-**-****. (Please don't recommend using input type password or changing font family)
If I understand you correctly try following snippet:
<!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>Vue</title>
</head>
<body>
<div id="app">
<input type="text" #input="onInput" v-model="someData" maxlength="11" />
</div>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js"></script>
<script>
Vue.filter("uppercase", function (value) {
let ssnValue =value
if(value.length === 3 || value.length === 6) {
ssnValue = value + '-'
}
console.log('fil',ssnValue)
return ssnValue.replace(/\d/g, '*')
});
const app = new Vue({
el: "#app",
data() {
return {
someData: "",
maskedData: "",
};
},
computed: {
getMaskedData() {
return this.maskedData;
},
},
methods: {
onInput(e) {
let originalString = e.data
if(!!originalString)
this.maskedData += originalString;
console.log('mask', e.data)
if(e.data) this.someData = this.$options.filters.uppercase(e.target.value);
},
},
});
</script>
</body>
</html>
I saw one of the links that you put in your question there is a format function which you can use:
function format(input, format, sep) {
input = input.replaceAll("-", "");
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
Vue.filter("uppercase", function (value) {
let ssnValue = format(value, [3, 3, value.length - 6], "-");
console.log("fil", ssnValue);
return ssnValue.replace(/\d/g, "*");
});

How to calculate cashback value using .reduce() method from input value?

I need to make a form where the user can enter the name of the purchase and its value. With each addition, the cashback costs should be calculated automatically (via reduce method). Cashback is 0.5%. All purchases must be contained in the purchases array and have exactly three properties:
id - number
name - string (name of Purchase)
price - number (price of Purchase)
I can't seem to figure out how to use reduce method to calculate cashback value. Besides each cashback value, total cashback should be displayed as well.
let nextId = 1;
const purchases = [];
const cashback = 0.005;
const commentForm = document.querySelector('[data-id="purchase-form"]');
const nameInput = commentForm.querySelector('[data-input="name"]');
const priceInput = commentForm.querySelector('[data-input="price"]');
const button = commentForm.querySelector('[data-input="price"]');
const purchasesList = document.querySelector('[data-id="purchases-list"]');
button.addEventListener('click', () => {
if (nameInput.value != '' && priceInput.value != '') {
purchases.push({
id: nextId++,
name: nameInput.value,
price: priceInput.value,
});
}
createElement(nameInput.value);
nameInput.value = '';
});
function createElement(ci) {
const newPurchase = document.createElement('li');
newPurchase.setAttribute('data-comment-id', nextId - 1);
newPurchase.textContent = `${ci} for sum of ${priceInput.value} $. (cashback- ${cashbackSum})`;
purchasesList.appendChild(newPurchase);
}
function cashbackSum() {
return Number(priceInput, 10) * cashback;
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="purchase-form">
<input data-input="name" />
<input data-input="price" />
<button type="button" data-action="add">Add</button>
</form>
<ul data-id="purchases-list"></ul>
<div>Total cashback is: <span data-id="total cashback"></span></div>
</div>
<script src="./js/app.js"></script>
</body>
</html>
There seemed to be a few bugs in the given snippet:
You are not getting the value of input box on each click so array is not going to contain the new values. [Make them let instead of const and fetch value on each button click event]
CashbackSum function was not being called.
Created a function for totalCashback that uses the reduce method of array to get the total cashback sum.
let nextId = 1;
const purchases = [];
const cashback = 0.005;
const commentForm = document.querySelector('[data-id="purchase-form"]');
let nameInput = commentForm.querySelector('[data-input="name"]');
let priceInput = commentForm.querySelector('[data-input="price"]');
const button = commentForm.querySelector('[data-action="add"]');
const purchasesList = document.querySelector('[data-id="purchases-list"]');
const totalCashback = document.querySelector('[data-id="total cashback"]');
const errorMsg = document.querySelector('[data-id="error"]');
button.addEventListener('click', () => {
nameInput = commentForm.querySelector('[data-input="name"]');
priceInput = commentForm.querySelector('[data-input="price"]');
if (nameInput.value != '' && priceInput.value != '') {
purchases.push({
id: nextId++,
name: nameInput.value,
price: priceInput.value,
});
createElement(nameInput.value);
nameInput.value = '';
errorMsg.textContent = '';
totalCashback.textContent = calculateTotalCashback() + ' $.';
}else{
errorMsg.textContent = 'Please fill both the fields: [name and price]';
}
});
function createElement(ci) {
const newPurchase = document.createElement('li');
newPurchase.setAttribute('data-comment-id', nextId - 1);
newPurchase.textContent = `${ci} for sum of ${priceInput.value} $. (cashback- ${cashbackSum()})`;
purchasesList.appendChild(newPurchase);
}
function cashbackSum() {
return Number(priceInput.value, 10) * cashback;
}
function calculateTotalCashback() {
return purchases.reduce((sum, item) => {
return sum + (parseFloat(item.price, 10) * cashback);
}, 0);
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="purchase-form">
<input data-input="name" />
<input data-input="price" />
<button type="button" data-action="add">Add</button>
<br /><span data-id="error"></span>
</form>
<ul data-id="purchases-list"></ul>
<div>Total cashback is: <span data-id="total cashback"></span></div>
</div>
<script src="./js/app.js"></script>
</body>
</html>

Change css display of multiple elements using class in javascript

Fairly new to Javascript here. I have a to do list, and I am in the process of adding a feature to Hide all checked items (which have a class .checked).
The idea i have, is to add a display property to the class(that all checked items receive) but how do I do it? Is there any other way for me to be able to add a display property to all of the checked items?
Here's the code (didn't include the other css as it was unnecesary):
//ADD NEW ELEMENT SECTION
function newElement() {
var inputval = document.getElementById('inputnewlist').value;
var li = document.createElement('li');
var lichild = document.createTextNode(inputval);
li.appendChild(lichild);
if (inputval === '') {
alert('you must put something in the textbox!');
} else {
document.getElementById('mylist').appendChild(li);
}
document.getElementById('inputnewlist').value = "";
//REMOVE BUTTON SECTION
var button = document.createElement('button');
var buttonval = document.createTextNode('x');
button.classList.add("exit");
button.appendChild(buttonval);
li.appendChild(button);
var exit = document.querySelectorAll('.exit');
for (b = 0; b < exit.length; b++) {
exit[b].addEventListener('click', removeButtonParent);
}
}//end of create newelement function
var exit = document.querySelectorAll('.exit');
for (z = 0; z < exit.length; z++) {
exit.addEventListener('click', removeButtonParent);
}
function removeButtonParent() {
event.target.parentElement.remove();
}
//ENTER KEY PRESS-BUTTON PRESS
function enterfunction(event) {
var key = document.getElementById('inputnewlist');
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('addbutton').click();
}}
//CHECK BUTTON SECTION
var list = document.querySelector('ul');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
//HIDE CHECKED LIST ITEMS
function hideCheck() {
if (event.target.checked === true) {
var checkLI = document.querySelectorAll('.checked');
checkLI.style.display = "none";
}
else {
var checkliELSE = document.querySelectorAll('.checked');
checkLI.style.display = "";
}
}
.checked {
background-color: darkgrey;
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div id="formcontainer">
<h1 class="title"> To Do List </h1>
<input type="text" name="inputnewlist" id="inputnewlist" placeholder="Add thing to do.." onkeydown="enterfunction(event)">
<button onclick="newElement()" class="addbutton" id="addbutton">Add</button>
</div>
<ul id="mylist">
</ul>
<input type="checkbox" id="hidecheck" onchange="hideCheck()"> <label for="hidecheck"> Hide the checked list items</label>
<script src="scripts.js"></script>
</body>
You can try the following code by adding the style 1 by 1.
function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}

No output from javascript function

I am really new to programming and this has had me stumped for days. I'm trying to do a really simple postage calculator. The function on its own works fine but when I tried to link it to user input im getting no output. Any help with this would be much appreciated.
Here's what I have been trying..
<!DOCTYPE html>
<html>
<head>
<title>postage calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<div>Postage Calculator</div>
<input id="amount" type="text" name="purchasePrice" placeholder="0" />
<input id="submit" type="submit" value="submit" />
<script type="text/javascript">
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
function aberdeen(){
var weight = parseFloat(amount.value) || 0;
if(weight>0 && weight<500){
return total = 3.50;
}
else if(weight<501 && weight<750){
return total = 4.30;
}
else if(weight<751 && weight<1000){
return total = 5.10;
}
else if(weight<1001 && weight<1250){
return total = 5.90;
}
else if(weight<1251 && weight<1500){
return total = 6.70;
}
else if(weight<1501 && weight<1750){
return total = 7.50;
}
else if(weight<1751 && weight<2000){
return total = 8.30;
}
else{
return 0;
}
}
submit.addEventListener("click", aberdeen, false);
</script>
</body>
</html>
You need to have element that will have the output of the calulation like:
<div id="output"></div>
var output = document.getElementById('output');
submit.addEventListener("click", function() {
output.innerHTML = aberdeen();
}, false);
You need to bind the eventListeners after the elements you are listening to are loaded.
The output has to be displayed somewhere. It can be either displayed in a textbox, a HTML-element or a simply alert() -box. I have used a text box in my example using element.
Also I created a working version of your code:
<!DOCTYPE html>
<html>
<head>
<title>postage calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<div>Postage Calculator</div>
<input id="amount" type="text" name="purchasePrice" placeholder="0" />
<input id="submit" type="submit" value="submit" />
<input id="userPays" type="text" name="userPays" />
<script type="text/javascript">
function aberdeen(amount){
var weight = parseFloat(amount) || 0;
if(weight>0 && weight<500){
return 3.50;
}
else if(weight<501 && weight<750){
return 4.30;
}
else if(weight<751 && weight<1000){
return 5.10;
}
else if(weight<1001 && weight<1250){
return 5.90;
}
else if(weight<1251 && weight<1500){
return total = 6.70;
}
else if(weight<1501 && weight<1750){
return 7.50;
}
else if(weight<1751 && weight<2000){
return 8.30;
}
else{
return 0;
}
}
window.onload = function() {
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
var userPays = document.getElementById("userPays");
function count(){
userPays.value = aberdeen(amount.value);
}
submit.addEventListener("click", count, false);
}
</script>
</body>
</html>
See demo at: http://codepen.io/anon/pen/zxaaQe
Make sure your logic to calculate values is correct as some commenters have suggested.

Categories

Resources