javascript button is not working based on code - javascript

I am trying to make login button enabled and color change to darker blue when there is at least one input for both id and password. (I have not implemented enabling portion yet.) Yet, above code does not seem to work. Could anyone help? Thanks!
const button = document.getElementById('button');
const idbar = document.getElementsByClassName('id-bar')[0];
const pwbar = document.getElementsByClassName('password-bar')[0];
const bar = document.getElementById('input')
bar.addEventListener("keyup", () =>{
const id = idbar.value;
const pw = pwbar.value;
if (id.length > 0 && pw.length > 0) {
button.style.backgroundColor = "#0095F6"
} else {
button.style.backgroundColor = "#C0DFFD"
}
});
<head>
<script src="js/login.js"></script>
</head>
<body>
<div class = wrapper>
<input id = "input" class = "id-bar" type = "text" placeholder = "email">
<input id = "input" class = "password-bar" type = "password" placeholder = "password">
<button id = "button">login</button>
</div>
</body>

id should be unique...
if not using id
const button = document.getElementById('button');
const idbar = document.getElementsByClassName('id-bar')[0];
const pwbar = document.getElementsByClassName('password-bar')[0];
const bar = document.getElementsByTagName("input");
[...bar].forEach(bar => {
bar.addEventListener("keyup", () =>{
const id = idbar.value;
const pw = pwbar.value;
if (id.length > 0 && pw.length > 0) {
button.style.backgroundColor = "#0095F6"
} else {
button.style.backgroundColor = "#C0DFFD"
}
});
})
<head>
<script src="js/login.js"></script>
</head>
<body>
<div class = wrapper>
<input id = "input" class = "id-bar" type = "text" placeholder = "email">
<input id = "input" class = "password-bar" type = "password" placeholder = "password">
<button id = "button">login</button>
</div>
</body>

So the problem with your code is that you are using id for targeting two element which is not possible and many have answered it, but I have a different suggestion which is CSS.
.submit {
background-color: #c0dffd;
}
.email-input:valid + .password-input:valid + .submit {
background-color: #0095f6;
}
<input type="text" class="email-input" required />
<input type="password" class="password-input" required />
<button class="submit">Submit</button>
You can even check whether email is valid or not just by adding type="email" in email input !

Your ids/classes are kind of all over the place, and as #dangerousmanleesanghyeon mentions, they don't conform to proper usage. Might be worth your time briefly reading up on how to use them correctly, via MDN: CSS selectors.
Anyway, I've refactored your code a little, and replaced the getElementBys with more versatile querySelectors, which is a great method to use, and might save you from some future headaches along your coding journey.
Just a note: querySelectorAll (used to get both the bars) returns a NodeList, which I've had to make into an Array in order to use map. This might feel a little complex right now, but these are useful concepts to familiarise yourself with!
const button = document.querySelector('#button')
const idbar = document.querySelector('#idInput')
const pwbar = document.querySelector('#passwordInput')
const bars = document.querySelectorAll('.input')
Array.from(bars).map(bar => bar.addEventListener("keyup", () => {
const id = idbar.value
const pw = pwbar.value
if (id.length > 0 && pw.length > 0) {
button.style.backgroundColor = "#0095F6"
} else {
button.style.backgroundColor = "#C0DFFD"
}
}))
<head>
<script src="js/login.js"></script>
</head>
<body>
<div class=wrapper>
<input id="idInput" class="input" type="text" placeholder="email">
<input id="passwordInput" class="input" type="password" placeholder="password">
<button id="button">login</button>
</div>
</body>

Just interchange the id & class values of inputs and changed the JS code accordingly. id must be unique.
const bars = document.getElementsByClassName('input');
const idbar = document.getElementById('id-bar');
const pwbar = document.getElementById('password-bar');
const button = document.getElementById('button');
for (bar of bars) {
bar.addEventListener("keyup", () => {
const id = idbar.value;
const pw = pwbar.value;
button.style.backgroundColor = (id.length && pw.length) ? "#0095F6" : "#C0DFFD"
});
}
<div class = wrapper>
<input id="id-bar" class="input" type="text" placeholder="email">
<input id="password-bar" class="input" type="password" placeholder="password">
<button id="button">login</button>
</div>

Related

Why is my input value equal '' when I retrieved with a button click event?

Why does the activityInput.value always equal an empty string. This seems very simple, I feel stupis asking something so simple but I cant get it to work. Please help me!
function addActivityListEntry(){
let activityListContainer = document.getElementById('activityList');
let newActivity = document.querySelector("#activityListInput").value
console.log(newActivity)
};
let activitySubmitButton = document.getElementById('activitySubmit');
activitySubmitButton.addEventListener('click', e => {
e.preventDefault();
addActivityListEntry()
})
<div id = "activityListContainer">
<input type ="text" class = "input" value = '' id = "activityListInput" name = "activityListInput" >
<label for = 'activityListInput'></label>
<button class = "button" id = "activitySubmit">
submit activity
</button>
<div id = 'activityList' ></div>
</div>
I can't seem to find where there should be an
activityInput.value
all you have is an
activityListInput.value
This html file should work and shows the logs for "activityListInput"
<!DOCTYPE html>
<head></head>
<body>
<div id = "activityListContainer">
<input type ="text" class = "input" value = '' id = "activityListInput" name = "activityListInput" >
<label for = 'activityListInput'></label>
<button class = "button" id = "activitySubmit">
submit activity
</button>
<div id = 'activityList' ></div>
</div>
</html>
<script>
function addActivityListEntry(){
let activityListContainer = document.getElementById('activityList');
let newActivity = document.querySelector("#activityListInput").value
console.log(newActivity)
};
let activitySubmitButton = document.getElementById('activitySubmit');
activitySubmitButton.addEventListener('click', e => {
e.preventDefault();
addActivityListEntry()
})
</script>
</body>

Element renders each time button is clicked

For the sake of practice I am trying to render an element on submitting the form but each time I click the button element renders on the page but it should render only once in the case of an invalid value.
My question is how to execute function renderError() only once, when Submit button is clicked?
The code I'm trying to accomplish this with is:
const form = document.querySelector('.form')
const renderError = () => {
const newElement = document.createElement('div')
newElement.className = 'error'
newElement.innerHTML = `
<img class="error__icon" src="images/icon-error.svg" alt="error icon" />
<p class="error__message">Please provide a valid email</p>
`
const rootElement = document.getElementById('error__container')
rootElement.append(newElement)
}
const validateForm = () => {
const isValid = /^[^\s#]+#[^\s#]+\.[^\s#]+$/
if (isValid.test(email.value)) {
// return something
} else {
renderError()
}
}
form.addEventListener('submit', (e) => {
e.preventDefault()
validateForm()
})
<div class="form__container">
<form class="form" novalidate>
<input type="email" name="email" id="email" aria-label="Email" placeholder="Email Address" />
<div id="error__container"></div>
<button class="submit">
<img src="images/icon-arrow.svg" alt="submit icon">
</button>
</form>
</div>
Don't create a new error element each time. Try to find the one created before (by id, for example). Create it only if you need it. This is often called "lazy" initialization.
// lazily return the error element (create it if we can't find it)
const errorElement = () => {
let element = document.getElementById('errorElement')
if (!element) {
element = document.createElement('div')
element.className = 'error'
element.id = 'errorElement';
const rootElement = document.getElementById('error__container')
rootElement.append(element)
}
return element
}
let count = 0
const validateForm = () => {
const isValid = /^[^\s#]+#[^\s#]+\.[^\s#]+$/
if (isValid.test(email.value)) {
// return something
} else {
const element = errorElement();
element.innerHTML = `something went wrong ${++count} times`
}
}
const form = document.getElementById('myform')
form.addEventListener('submit', (e) => {
e.preventDefault()
validateForm()
})
<div class="form__container">
<form id="myform" class="form" novalidate>
<input type="email" name="email" id="email" aria-label="Email" placeholder="Email Address" />
<div id="error__container"></div>
<button class="submit">Button
</button>
</form>
</div>
One solution: you can clear the contents of the rootElement before re-rendering:
const renderError = () => {
const newElement = document.createElement('div')
newElement.className = 'error'
newElement.innerHTML = `
<img class="error__icon" src="images/icon-error.svg" alt="error icon" />
<p class="error__message">Please provide a valid email</p>
`
const rootElement = document.getElementById('error__container')
rootElement.innerHTML = ""; // <-- Empty before appending
rootElement.append(newElement)
}
Another solution would be to add the newElement in the HTML, hide it using visibility: hidden and then toggle a class on/off that will turn the visibility value to visible and hidden. This way, when the render error runs, it will just add a special class that will display the error element and upon clicking again the element will just get the class enabled again without re-appearing.

it seems that i only have one key in my localstorage and it keeps storing all the values into it(localstorage)

hey i am trying to make a phonebook where everytime i add someones name and phonenumber it displays it into the front page and then i can remove or edit...
now i have tried to add a remove function so it removes only the one row or name i choose after many tries i noticed in the application(in the inspect where the developers tools) there is only one key and it seems like i am storing all the arrays (values) into it , now what if i want to remove one value only from the key i am not sure if its possible
maybe i have to make it so i have multiple keys with each key with its own value i am not sure
this is my js code
"use strict";
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
} //end of function
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
} //end of function
cancelOverlay("cancelOverlay", "formContainer");
//
let phoneArray = [];
window.onload = init;
const submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", function addPerson() {
const person = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
};
if (person.name != "" && person.phoneNumber != "") {
phoneArray = JSON.parse(localStorage.getItem("person")) || [];
phoneArray.push(person);
localStorage.setItem("person", JSON.stringify(phoneArray));
phoneArray = localStorage.getItem("person");
phoneArray = JSON.parse(phoneArray);
window.location.reload(true);
} //end if
} //end addPerson)
);
function createLayout(person) {
const divv = document.getElementById("outPutContainer");
let row = document.createElement("ul");
row.innerHTML = `
<li>${person.name} </li>
<li>${person.phoneNumber} </li>
<button class="insideRemoveBtn"> - </button>
`;
divv.appendChild(row);
} //end of function
function getPersonArray() {
return JSON.parse(localStorage.getItem("person"));
} //end of function
function init() {
const personArray = getPersonArray();
for (let i = 0; i < personArray.length; i++) {
const person = personArray[i];
createLayout(person);
const insideRemoveBtn = document.querySelector(".insideRemoveBtn");
insideRemoveBtn.addEventListener("click", function removeSingleItem() {
localStorage.removeItem('person');
location.reload(true);
});
}
} //end of function
const removeAllBtn = document.getElementById("removeAllBtn");
removeAllBtn.addEventListener("click", function removeAll() {
localStorage.clear();
location.reload(true);
});
and this is my html code if needed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PhoneBook</title>
<link rel="stylesheet" href="Css/Whole.css">
<script defer src="JavaScript/PU.js"></script>
</head>
<body>
<h1>PhoneBook</h1>
<div class="childContainer">
<div class="buttonsContainer">
<div>
<input type="search" placeholder="search" class="searchBar"></div>
<div class="buttonsRightSide"> <button value="submit" id="addBtn" class="addBtn">+</button>
<button value="submit" id="removeAllBtn" class="removeAllBtn">-</button>
<button value="submit" id="saveBtn" class="saveBtn">*</button></div>
</div>
<div class="formContainer">
<form class="addForm" id="addForm">
<h2>Create Contact</h2>
<label for="name">First name*:</label>
<input id="name" type="text" pattern="[A-Z][a-zA-Z]{3,7}" required><br>
<label for="phoneNumber">Phone number*:</label>
<input id="phone" type="number" pattern="[0][5][0-8][ -]?\d{7}" required><br>
<label for="Adress">Address:</label>
<input type="text" id="Address"><br>
<label for="Email">Email:</label>
<input type="email" id="Email"><br>
<label for="Description">Description:</label>
<textarea type="text" id="Description"></textarea><br>
<div class="sendCancelButtons">
<button type="submit" class="submitButton" id="submitButton">Send</button>
<button value="submit" class="cancelOverlay">Cancel</button></div>
</form>
</div>
<div id="outPutContainer" class="outPutContainer">
</div>
</div>
</body>
</html>
any hints and suggestions are welcome and thanks in advance <3
From what I understood from your question, you are storing all your phonebook data inside person key. For deleting any specific "person" from the localStorage you can parse the array once again and then remove that "person" from array and save it back to localStorage. I'm assuming you want to remove person by it's phone number.
function removeByPhoneNumber(phoneNumber){
const prevArray = JSON.parse(localStorage.getItem("person")) || [];
const newArray = prevArray.filter(_person => _person.phoneNumber !== phoneNumber)
localStorage.setItem("person", JSON.stringify(newArray))
}

After creating array of objects how to update a key value of object? JavaScript

I got something simple but I'm obviously too stupid.
I have two inputs in my HTML. 1st is company and 2nd is shares. I'm creating UL with the companies. The thing is I want to do that when I enter a company name that already exist in the array I want to update the shares of that company only. I will share the code I made so far.
<body>
<form>
<input id="company" placeholder="Company" type="text" />
<input id="input" placeholder="Shares" type="number" />
<button id="btn">Add</button>
</form>
<ul id="content"></ul>
</body>
And the JavaScript code is here:
const button = document.getElementById("btn");
const content = document.getElementById("content");
let companiesArray = [];
function myCompany(e) {
e.preventDefault();
const inputShares = document.getElementById("input").value;
const inputCompany = document.getElementById("company").value;
let obj = {
company: inputCompany,
shares: inputShares,
};
for (const item of companiesArray) {
if (item.company === obj.company) {
//TO DO
console.log("Match");
return;
}
}
const li = document.createElement("li");
content.appendChild(li).textContent = `${obj.company} - ${obj.shares}`;
companiesArray = [...companiesArray, obj];
console.log(companiesArray);
}
button.addEventListener("click", myCompany);
So again, when I enter a unique company => li is created in the ul. If I enter the same company I just want to update the shares without adding new li.
if (item.company === obj.company) {
//TO DO
const list = document.getElementsByTagName('li')
const element = [...list].filter((item) => item.innerText.split(" ")[0] === obj.company)[0]
element.innerText = `${obj.company} - ${obj.shares}`
console.log("Match");
return;
}
Hope this will help :)

How I can display the form data in the same page without submit the form?

I have a form in HTML and I want to display the form text input data on the same page but before pressing the submit button.
Mean, When Users put the data in the form it must display below the form on same page.
It's mean that I want to show all data before submitting the form.
I know this code will not work as i want
var strText = document.getElementById("textone");
document.write(strText.value);
var strText1 = document.getElementById("textTWO");
document.write(strText1.value);
}
This is how I would do it by directly manipulating the DOM:
const input = document.getElementById('textInput');
const textElement = document.getElementById('displayText');
function updateValue(e) {
textElement.textContent = e.target.value;
}
input.addEventListener('input', updateValue);
<input type="text" id="textInput">
<p>value from input:</p>
<div id="displayText"></div>
There are also javascript libraries like VueJS and ReactJS that can help you do this more easily and efficiently.
This is an example of something like what you would want to do in VueJS: https://v2.vuejs.org/v2/examples/index.html
I've prepared an example of general functioning, I hope you like it. It may not be exactly what you want, but if it is, please tell me.
const myForm = document.getElementById("myForm");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const nameOutput = document.getElementById("nameOutput");
const emailOutput = document.getElementById("emailOutput");
let nameSpan = document.getElementById("name");
let emailSpan = document.getElementById("email");
myForm.addEventListener("submit", e => {
e.preventDefault();
alert(`NAME: ${nameInput.value}, EMAİL : ${emailInput.value}`)
// select name , mail
nameSpan.innerText = nameInput.value;
emailSpan.innerText = emailInput.value;
// clear ınputs
nameInput.value = "";
emailInput.value = ""
})
showData();
function showData() {
nameInput.addEventListener("keyup", e => {
nameOutput.value = e.target.value;
})
emailInput.addEventListener("keyup", e => {
emailOutput.value = e.target.value;
})
}
<form id="myForm">
<input type="text" id="nameInput" placeholder="your name">
<input type="text" id="emailInput" placeholder="your email">
<button type="submit" id="getInputValue"> Get Input Value </button>
</form>
<div id="values" style="margin-top: 100px;">
<input type="text" placeholder="NAME" id="nameOutput">
<input type="text" placeholder="EMAİL" id="emailOutput">
</div>
<div>
<p>Your name : <span id="name"></span></p>
<p>Your email : <span id="email"></span></p>
</div>

Categories

Resources