jQuery/JS: delete object from array and DOM - javascript

I am learning JS and jQuery. As an exercise, I am trying to create a basic contact list. I need to be able to add and delete contacts from the list.
But I am having some bugs in my result. I can't find the cause of it. If anyone can advise? I would be most gratefull.
BUG 1:
When running the snippet below, you will see some sample contacts generated in the list. You can delete a contact just fine. You can also add a contact. But after adding a contact, the delete buttons stop working.
First I thought the issue was probably a missing character in my .html() method on the contacts objects. But I see no errors there. Anyone?
BUG 2:
Inside the $renderContacts function. You can see the const html. This should replace the let html and for loop below. And it works for long list of contacts. But the first contact is rendered as [object Object]. I don't see the cause. Might these 2 bugs be related?
Please advise.
Many thanks! :)
$(document).ready(function() {
// Array to store all contacts
let contactsArr = [];
// counter to create incrementing ID
let contactID = 0;
// Constructor for contact objects
function Contact(firstName, lastName, email, phone, address) {
this._id = contactID += 1;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.address = address;
contactsArr.push(this);
};
// Some getters, setters and a methods for contact objects
Contact.prototype = {
constructor: Contact,
set(id) {
console.log(`ID is generated on input and may not be changed`)
},
get id() {
return this._id;
},
set firstName(firstName) {
this._firstName = firstName;
},
get firstName() {
return this._firstName;
},
set lastName(lastName) {
this._lastName = lastName;
},
get lastName() {
return this._lastName;
},
set email(emailaddress) {
this._email = emailaddress;
},
get email() {
return this._email;
},
set phone(phone) {
this._phone = phone;
},
get phone() {
return this._phone
},
set address(address) {
this._address = address;
},
get address() {
return this._address
},
toHTML() {
const renderCell = (content, cssClass = "") => `<div class="table-cell ${cssClass}">${content}</div>`;
const deleteContact = `<span title="Delete contact" class="delete-contact far fa-trash-alt fa-sm"></span>`;
const rowActions = renderCell(deleteContact, "text-right contact-actions");
return '<div class="table-row">' +
renderCell(this.id, "contact-id text-right") +
renderCell(this.firstName, "first-name") +
renderCell(this.lastName, "last-name") +
renderCell(this.email, "email") +
renderCell(this.phone, "phone") +
renderCell(this.address, "address") +
rowActions + '</div>';
},
};
// SAMPLE CONTACTS
new Contact("John", "Cubico", "mymail#mail.com", "111-555-6666", "Belgium");
new Contact("Lisa", "The Sailor", "mymail#mail.com", "111-666-7777", "Spain");
new Contact("Christophe", "From next door", "mymail#mail.com", "111-777-8888", "Germany");
new Contact("Aïsha", "From elsewere", "mymail#mail.com", "111-888-9999", "Brussels, Holland");
// Render Samples
function $renderContacts(arr = contactsArr) {
//const html = arr.reduce((all, one) => all += one.toHTML()); // ==>> 1st not rendering
let html = ``;
for (let i = 0; i < arr.length; i++) {
html += arr[i].toHTML();
};
$("#contacts-list").append(html);
};
$renderContacts();
// BUTTONS & ACTIONS
// Add contact
$("#add-contact").on("click", () => {
const $firstName = $("#first-name").val();
const $lastName = $("#last-name").val();
const $email = $("#email").val();
const $phone = $("#phone").val();
const $address = $("#address").val();
const contact = new Contact($firstName, $lastName, $email, $phone, $address); // create contact
$("#contacts-list").append(contactsArr[contactsArr.length - 1].toHTML()); // add contact to DOM
});
// Delete contact
$(".delete-contact").on("click", (event) => {
const arr = contactsArr.slice();
const $id = Number($(event.currentTarget).closest(".table-row").find(".contact-id").text());
const i = arr.findIndex(contact => contact.id == $id);
contactsArr = arr.slice(0, i).concat(arr.slice(i + 1)); // delete from array of contacts
$(event.currentTarget).closest(".table-row").remove(); // delete only this contact from DOM
});
});
html {}
.active {}
.inactive {
color: #b8b8b8;
}
.table td,
.table th {
padding: 0.5rem;
}
.text-large {
font-size: 1.5rem;
}
.relative {
position: relative;
}
/*** Search ***/
#search-input {
font-size: 2rem;
font-weight: 300;
}
span#search-btn {
position: absolute;
right: 0;
top: 0;
width: 50px;
height: 47px;
padding: 10px;
box-sizing: border-box;
font-size: 1.6rem;
line-height: 34px;
}
/*** Contacts table ***/
.table-header {
padding: 15px 0 5px;
}
.table-row {
display: grid;
grid-template-columns: 30px repeat(5, 1fr) 100px;
grid-column-gap: 20px;
margin: 3px 0;
padding: 2px 0;
background: #f0f0f0;
}
.table-cell {
padding: 3px;
}
.editable-cell {
background: rgba(255, 255, 255, 0.6);
}
.contact-actions span {
line-height: 18px;
padding: 3px;
display: inline-block;
width: 26px;
text-align: center;
}
/*** Form ***/
#form-new-contact {
align-items: end;
margin: 0 -15px;
padding: 15px;
}
#add-contact {
width: 100%;
}
<html>
<head>
<title>jQuery contacts app</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<header>
<div class="container text-center mt-4 mb-4">
<h1>jQuery contacts app</h1>
</div>
</header>
<main>
<div class="container">
<form id="form-new-contact" action="" method="POST" class="table-row mt-4 mb-4">
<div class="text-center"><span class="fas fa-user-plus fa-sm mb-2"></span></div>
<div class="">
<label for="first-name">First name:</label>
<input name="first-name" id="first-name" class="form-control form-control-sm" type="text" value="Voornaam" placeholder="John" required>
</div>
<div class="">
<label for="last-name">Last name:</label>
<input name="last-name" id="last-name" class="form-control form-control-sm" type="text" value="Achternaam" placeholder="Doe" required>
</div>
<div class="">
<label for="email">Email:</label>
<input name="email" id="email" class="form-control form-control-sm" type="email" value="E-mailadres" placeholder="john#doe.com" required>
</div>
<div class="">
<label for="phone">Phone:</label>
<input name="phone" id="phone" class="form-control form-control-sm" type="tel" value="Telefoon/GSM" placeholder="555-666-8989" required>
</div>
<div class="">
<label for="address">Address:</label>
<input name="address" id="address" class="form-control form-control-sm" type="text" value="Adres" placeholder="Somewhere" required>
</div>
<div class="">
<button id="add-contact" type="button" class="btn btn-sm btn-success"><i class="fas fa-plus-circle mr-2"></i>Add</button>
</div>
</form>
<div class="table">
<div class="table-row table-header">
<div id="id-header" class="text-right">
<h3 class="h6">ID</h3>
</div>
<div id="first-name-header" class="">
<h3 class="h6">Firstname</h3>
</div>
<div id="last-name-header" class="">
<h3 class="h6">Lastname</h3>
</div>
<div id="email-header" class="">
<h3 class="h6">Email</h3>
</div>
<div id="phone-header" class="">
<h3 class="h6">Phone</h3>
</div>
<div id="address-header" class="">
<h3 class="h6">Address</h3>
</div>
<div class="text-right">
<h3 class="h6">Actions</h3>
</div>
</div>
<div id="contacts-list" class="">
</div>
</div>
</div>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

BUG1:
You can't fire on click function on dynamically generated DOM element like that.
Add event listener to your element (using pure JS):
elem.addEventListener("click", func, false);
Or change syntax of your click function to this (using jQuery):
$(document).on("click",'.delete-contact', (event) => {
// your code here
});
BUG2:
I don't know why this function acts like that, but you always have to pass default string parameter. Look to the next lines I made:
let html = arr.reduce((all, one) => all += one.toHTML(), '');
Working fiddle

Related

Can a function be inside another function?

I am working on a library project but my function called changeColor inside the readStatus function does not appear to be working.
I've tried separating it but having two event listeners on the same button does not appear to work. My goal is for readStatus function to allow a user to update the status of a book from no to yes when finished with the book.
Likewise, I want to change the background color of the div (class: card) when yes to be green and no to be red.
Can anyone tell me what I'm doing wrong?
let myLibrary = [];
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
function addBookToLibrary(title, author, pages, read) {
let book = new Book(title, author, pages, read);
myLibrary.push(book);
displayOnPage();
}
function displayOnPage() {
const books = document.querySelector(".books");
const removeDivs = document.querySelectorAll(".card");
for (let i = 0; i < removeDivs.length; i++) {
removeDivs[i].remove();
}
let index = 0;
myLibrary.forEach((myLibrarys) => {
let card = document.createElement("div");
card.classList.add("card");
books.appendChild(card);
for (let key in myLibrarys) {
let para = document.createElement("p");
para.textContent = `${key}: ${myLibrarys[key]}`;
card.appendChild(para);
}
let read_button = document.createElement("button");
read_button.classList.add("read_button");
read_button.textContent = "Read ";
read_button.dataset.linkedArray = index;
card.appendChild(read_button);
read_button.addEventListener("click", readStatus);
let delete_button = document.createElement("button");
delete_button.classList.add("delete_button");
delete_button.textContent = "Remove";
delete_button.dataset.linkedArray = index;
card.appendChild(delete_button);
delete_button.addEventListener("click", removeFromLibrary);
function removeFromLibrary() {
let retrieveBookToRemove = delete_button.dataset.linkedArray;
myLibrary.splice(parseInt(retrieveBookToRemove), 1);
card.remove();
displayOnPage();
}
function readStatus() {
let retrieveBookToToggle = read_button.dataset.linkedArray;
Book.prototype = Object.create(Book.prototype);
const toggleBook = new Book();
if (myLibrary[parseInt(retrieveBookToToggle)].read == "yes") {
toggleBook.read = "no";
myLibrary[parseInt(retrieveBookToToggle)].read = toggleBook.read;
} else if (myLibrary[parseInt(retrieveBookToToggle)].read == "no") {
toggleBook.read = "yes";
myLibrary[parseInt(retrieveBookToToggle)].read = toggleBook.read;
}
let colorDiv = document.querySelector(".card");
function changeColor() {
for (let i = 0; i < length.myLibrary; i++) {
if (myLibrary[i].read == "yes") {
colorDiv.style.backgroundColor = "green";
} else if (myLibrary[i].read == "no") {
colorDiv.style.backgroundColor = "red";
}
}
}
displayOnPage();
}
index++;
});
}
let add_book = document.querySelector(".add-book");
add_book.addEventListener("click", popUpForm);
function popUpForm() {
document.getElementById("data-form").style.display = "block";
}
function closeForm() {
document.getElementById("data-form").style.display = "none";
}
let close_form_button = document.querySelector("#close-form");
close_form_button.addEventListener("click", closeForm);
function intakeFormData() {
let title = document.getElementById("title").value;
let author = document.getElementById("author").value;
let pages = document.getElementById("pages").value;
let read = document.getElementById("read").value;
if (title == "" || author == "" || pages == "" || read == "") {
return;
}
addBookToLibrary(title, author, pages, read);
document.getElementById("data-form").reset();
}
let submit_form = document.querySelector("#submit-form");
submit_form.addEventListener("click", function (event) {
event.preventDefault();
intakeFormData();
});
* {
margin: 0;
padding: 0;
background-color: rgb(245, 227, 205);
}
.books {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
text-align: center;
margin: 20px;
gap: 10px;
}
.card {
border: 1px solid black;
border-radius: 15px;
padding: 10px;
}
.forms {
display: flex;
flex-direction: column;
align-items: center;
}
form {
margin-top: 20px;
}
select,
input[type="text"],
input[type="number"] {
width: 100%;
box-sizing: border-box;
}
.buttons-container {
display: flex;
margin-top: 10px;
}
.buttons-container button {
width: 100%;
margin: 2px;
}
.add-book {
margin-top: 20px;
}
#data-form {
display: none;
}
.read_button {
margin-right: 10px;
}
<!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="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="container">
<div class="forms">
<button class="add-book">Add Book To Library</button>
<div class="pop-up">
<form id="data-form">
<div class="form-container">
<label for="title">Title</label>
<input type="text" name="title" id="title" />
</div>
<div class="form-container">
<label for="author">Author</label>
<input type="text" name="author" id="author" />
</div>
<div class="form-container">
<label for="pages">Pages</label>
<input type="number" name="pages" id="pages" />
</div>
<div class="form-container">
<label for="read">Read</label>
<select name="read" id="read">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div class="buttons-container">
<button type="submit" id="submit-form">Submit Form</button>
<button type="button" id="close-form">Close Form</button>
</div>
</form>
</div>
</div>
<div class="books"></div>
</div>
<script src="script.js"></script>
</body>
</html>
A couple things needed.
First, you should put the readStatus and removeFromLibrary functions outside of the foreach loop.
Then I think you are wanting changeColor to run whenever readStatus is run. Either put the changeColor code directly inside the readStatus or put changeColor() inside readStatus.
I think you want the Book to not be a function but a class.

How to match user input with array data in JavaScript

I'm new in learning HTML, JavaScript and CSS. I'm stuck at this JavaScript code.
I'm trying to match user input on the searchbar with some city array list I already prepared, when the search result match the script will change the display style of element into showing the result of their search value, but until now the result always showing false value.
Is there any better way to do this? Is there something wrong with my code?
function searchRespond() {
if (document.getElementById("myInput").value.match(cities))
{
document.getElementById("areaCovered").style.display = "block";
}
else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search">
<div class="searchrespond" id="searchRespond">
<h id="areaCovered">YES! We cover your area destination</h>
<h id="areaNotCovered">We don't cover your area destination yet
<p id="searchResult"></p>
</h>
<h id="fillArea">Please fill your area destination first</h>
</div>
</form>
</div>
</div>
To do what you require you can use filter() to match the user's input to values in your array. You would be best to perform a case-insensitive match, which can be done by converting both values to the same case.
Note that this logic sets the notifications as hidden before the logic runs, so that the previous state of the search is removed.
In addition, I made a couple of improvements to the code. Firstly I stored the relevant elements in variables instead of accessing the DOM every time. This is slightly more performant, and makes the code a lot easier to read. I also used addEventListener() to bind events instead of inline event handlers in the HTML, which are bad practice and shouldn't be used. Lastly I converted the <h> elements to <h2 /> in this demo, as there is no <h> element in HTML.
const input = document.querySelector('#myInput');
const areaCovered = document.querySelector('#areaCovered');
const areaNotCovered = document.querySelector('#areaNotCovered');
const searchResult = document.querySelector('#searchResult');
const fillArea = document.querySelector('#fillArea');
const cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
document.querySelector('#search-from').addEventListener('submit', e => {
e.preventDefault();
const searchTerm = input.value.trim().toLowerCase();
fillArea.style.display = 'none';
areaCovered.style.display = 'none';
areaNotCovered.style.display = 'none';
if (!searchTerm) {
fillArea.style.display = 'block';
return;
}
let matches = cities.filter(city => city.toLowerCase() == searchTerm);
if (matches.length) {
areaCovered.style.display = 'block';
} else {
areaNotCovered.style.display = 'block';
}
});
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
.autocomplete {
width: 300px;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm" id="search-from">
<div class="autocomplete">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<button type="submit">Search</button>
<div class="searchrespond" id="searchRespond">
<h2 id="areaCovered">YES! We cover your area destination</h2>
<h2 id="areaNotCovered">We don't cover your area destination yet</h2>
<h2 id="fillArea">Please fill your area destination first</h2>
</div>
</form>
</div>
</div>
You can use javascript includes().
<script>
const fruits = ["Banana Aceh", "Orange", "Apple", "Mango"];
let str = "Banana Aceh"; //document.getElementById("myInput").value
if(fruits.some(v => str.includes(v))) {
console.log("Exists");
} else {
console.log("Did not Exists");
}
</script>
function searchRespond() {
let searchTerm = document.getElementById("myInput").value;
if (cities.find(city => city == searchTerm))
{
document.getElementById("areaCovered").style.display = "block";
}
else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search">
<div class="searchrespond" id="searchRespond">
<h id="areaCovered">YES! We cover your area destination</h>
<h id="areaNotCovered">We don't cover your area destination yet
<p id="searchResult"></p>
</h>
<h id="fillArea">Please fill your area destination first</h>
</div>
</form>
</div>
</div>
suggest to validate input by making first letter uppercase and rest lowercase to match the array values
with javascript indexOf function
function searchRespond() {
var input = document.getElementById("myInput").value;
var area2search = input.charAt(0).toUpperCase() + input.slice(1).toLowerCase(); /* make fist letter capital and rest lower case to match array */
if (cities.indexOf(area2search) > -1) {
document.getElementById("areaCovered").style.display = "block";
//In the array!
} else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];

form taking full width of the screen

I am building a sample project named Tennis Club Management using Javascript,HTML,CSS . In this project i have login html page & managePlayer html page. In manageplayer.html, i have two button namely Add Players and Show Players . On button click of Add Players,only then i want to show the form for registering the players.
The problem is when the form is created, the sidebar which automatically gets created on page load ( have created separate file sidebar.js ) gets lowered down when the form appears as form is taking full width
Below are the screenshots and code files
index.js
// --------------TESTING CODE FOR LOGIN PAGE LOGIN BUTTON CLICK----------------
var istableCreated = false;
var email, password;
document.querySelector(".loginbtn").addEventListener("click", (e) => {
email = document.querySelector(".email").value;
password = document.querySelector(".password").value;
document.querySelector(".labelemailerror").innerHTML = "";
document.querySelector(".labelpassworderror").innerHTML = "";
// ------------TESTING CODE FOR CHECKING VALIDATION AND PRINTING ERROR ON LABELS IF ANY-------------
if (email === "admin#wimbledon.com" && password === "rogerfederer") {
console.log("Login successfull....");
window.open("profile.html");
}
else if (email === "" && password === "") {
document.querySelector(".labelpassworderror").innerHTML = "Email and Password cannot be blank"
}
else if (email === "") {
document.querySelector(".labelemailerror").innerHTML = "Email cannot be blank";
}
else if (password === "") {
document.querySelector(".labelpassworderror").innerHTML = "Password cannot be blank"
}
else {
document.querySelector(".labelpassworderror").innerHTML = "Invalid Email or Password";
}
console.log(email, password);
e.preventDefault();
});
//------------------------------------MANAGE PLAYERS PAGE----------------------------------
//--------------------------------TESTING CODE FOR SHOWING PLAYERS OF MANAGE PLAYERS PAGE--------------------------
function showplayers() {
if(istableCreated==false){
istableCreated = true;
console.log(istableCreated);
//----------TESTING CODE FOR CREATING WRAPPER FOR BOOTSTRAP TABLE FOR RESPONSIVENESS--------
var myDiv = document.createElement("div");
myDiv.className = "table-responsive";
myDiv.id="table-responsive";
document.body.appendChild(myDiv);
//-----------TESTING CODE FOR CREATING BOOTSTRAP DYNAMIC TABLE USING JAVASCRIPT-------------
var myTable = document.createElement("table");
myTable.style.marginTop = "2%";
myTable.className = "table";
myTable.id="table";
document.body.appendChild(myDiv).appendChild(myTable);
var myThead = document.createElement("thead");
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead);
var myTr = document.createElement("tr");
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr);
var myThID = document.createElement("th");
myThID.scope = "col";
myThID.innerHTML = "ID";
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThID);
var myThName = document.createElement("th");
myThName.scope = "col";
myThName.innerHTML = "Name";
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThName);
var myThGender = document.createElement("th");
myThGender.scope = "col";
myThGender.innerHTML = "Gender";
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myThGender);
var mySubscription = document.createElement("th");
mySubscription.scope = "col";
mySubscription.innerHTML = "Subscription";
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(mySubscription);
var myfeeStatus = document.createElement("th");
myfeeStatus.scope = "col";
myfeeStatus.innerHTML = "Fee Status";
document.body.appendChild(myDiv).appendChild(myTable).appendChild(myThead).appendChild(myTr).appendChild(myfeeStatus);
}
else{
console.log(istableCreated);
}
}
function addplayers() {
console.log("add players clicked.....")
}
managePlayers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Players</title>
<!-- ADDING FONT AWESOME CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- ADDING BOOTSTRAP CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- ADDING STYLE.CSS -->
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<!-- ADDING BUTTONS LIKE SHOW PLAYERS, ADD PLAYERS USING CSS BOOTSTRAP -->
<button type="button" class="btn btn-secondary showplayers" onclick="showplayers();">Show Players</button>
<button type="button" class="btn btn-secondary addplayers" onclick="addplayers()">Add Players</button>
<!-- CREATING REGISTRATION FORM OF CUSTOMER -->
<form class="customerregistration">
<div class="container form-div">
<!-- ADDING ID AND DOB -->
<div class="row">
<div class="col">
<label>ID :</label>
<input type="text">
</div>
<div class="col">
<label>DOB :</label>
<input type="date" id="birthday" name="birthday">
</div>
</div>
<!-- ADDING NAME AND GENDER -->
<div class="row">
<div class="col">
<label>NAME :</label>
<input type="text" placeholder="Enter Name">
</div>
<div class="col">
<label>GENDER :</label>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
</div>
</div>
<!-- ADDING CONTACT NUMBER -->
<div class="row">
<div class="col">
<label>CONTACT :</label>
</div>
<div class="col">
<input type="text" placeholder="Enter Contact Number">
</div>
</div>
<!-- ADDING ADDRESS -->
<div class="row">
<div class="col">
<label>ADDRESS :</label>
</div>
<div class="col">
<textarea class="address" id="address" cols="25" rows="3"></textarea>
</div>
</div>
<!-- ADDING ID PROOF -->
<div class="row">
<div class="col">
<label>ID PROOF :</label>
<select class="idproof" id="idproof">
<option value="select">---Select---</option>
<option value="license">License</option>
<option value="aadhaar">Aadhaar</option>
<option value="passport">Passport</option>
</select>
</div>
<div class="col">
<input type="text">
</div>
</div>
<!-- ADDING MEMBERSHIP -->
<div class="row">
<div class="col">
<label>MEMBERSHIP :</label>
</div>
<div class="col">
<select class="idproof" id="idproof">
<option value="select">---Select---</option>
<option value="license">MONTHLY</option>
<option value="aadhaar">HALF YEARLY</option>
<option value="passport">ANNUALLY</option>
</select>
<label class="membership-package"></label>
</div>
</div>
<!-- ADDING SAVE BUTTON -->
<div class="row">
<button type="submit" class="btn-success">SAVE</button>
</div>
</div>
</form>
<!-- ADDING BOOTSTRAP JS -->
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
<!-- ADDING INDEX.JS -->
<script src="/js/sidebar.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
style.css
/* ---------------- SETTING CSS PROPERTIES OF PROFILE PAGE AND SIDE BAR---------------- */
body {
margin: 0;
font-family: "Lato", sans-serif;
}
.sidebar {
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
.sidebar a {
display: block;
color: black;
padding: 16px;
text-decoration: none;
}
.sidebar a.active {
background-color: #4CAF50;
color: white;
}
.sidebar a:hover:not(.active) {
background-color: #555;
color: white;
}
div.content {
margin-left: 200px;
padding: 1px 16px;
height: 1000px;
}
#media screen and (max-width: 700px) {
.sidebar {
width: 100%;
height: auto;
position: relative;
}
.sidebar a {float: left;}
div.content {margin-left: 0;}
}
#media screen and (max-width: 400px) {
.sidebar a {
text-align: center;
float: none;
}
}
.editadminprofile{
float: right;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE PLAYERS PAGE---------------- */
.showplayers{
margin-right: 30%;
margin-top: 5%;
float: right;
width: 15%;
}
.addplayers{
margin-right: 3%;
margin-top: 5%;
float: right;
width: 15%;
}
/* ---------------- SETTING CSS PROPERTIES OF TABLE OF MANAGE PLAYER PAGE ---------------- */
table{
table-layout: fixed;
}
table th, table td {
overflow: hidden;
}
th{
width: 5%;
}
Screenshot
Any solution please ?
If you just use left: 0, top: /* how far you want the sidebar to be from the top of page */ with position: fixed, that should keep it from moving.

Warning message when caps lock is on while entering password is not working and also initial scale is not recognized in google chrome only

I am using a JavaScript function to check if caps lock is on and on the console window I get "Uncaught TypeError: Cannot read property 'addEventListener' of null
at login.js:41"
In google chrome's console window I also get an error
"The key "intial-scale" is not recognized and ignored"
I tried searching for the causes of this problem and I saw people saying that this may be because the function is executed before the DOM runs so I tried adding window.onload before the function but it didn't fix the issue.
// array of objects to store adminstrators data
var usersObj =[
{
username: "karim",
password: "karim2019"
},
{
username: "nourhan",
password: "noura2019"
},
{
username: "nariman",
password: "nariman2019"
}
]
// function to authenticate login information and proceed to the next page
function getLoginInfo()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(i = 0; i < usersObj.length; i++)
{
if(username == usersObj[i].username && password == usersObj[i].password)
{
alert("Login successful..");
document.getElementById("loginf").action = "dashboard.html";
return
}
}
alert("Username or password is incorrect!");
document.getElementById("loginf").action = "login.htm";
}
var input = document.getElementById("password");
var text = document.getElementById("text");
input.addEventListener("keyup", window.onload=function(event)
{
if (event.getModifierState("CapsLock"))
{
text.style.visibility = "visible";
}
else
{
text.style.visibility = "hidden"
}
});
.row {
margin-top: 5%;
}
/* Bordered form */
form {
margin-top: 20%;
}
/* Full-width inputs */
input[type=text], input[type=password] {
width: 100%;
padding: 1% 2%;
margin: 1%;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
p{
display: none;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 1% 2%;
margin: 1%;
border: none;
cursor: pointer;
width: 100%;
}
/* Add a hover effect for buttons */
button:hover {
opacity: 0.8;
}
/* Add padding to containers */
.container {
padding: 1.5%;
}
/* The "Forgot password" text */
span.psw {
float: right;
padding-top: 1.5%;
}
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, intial-scale=1 maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="loginstyles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="login.js"></script>
<body>
<div class="row">
<div class="col"></div>
<div class="col">
<form id = "loginf" name="loginf" method="POST">
<div>
<h1>Account Login</h1>
</div>
<div><hr></div>
<div class="container">
<label for="username"><b>Username</b></label>
<input id="username" type="text" placeholder="Enter Username" name="username" required>
<label for="password"><b>Password</b></label>
<input id="password" type="password" placeholder="Enter Password" name="password" required>
<p id="text">WARNING!Caps Lock is ON.</p>
<label>
<input type="checkbox" checked="checked" name="remember">Remember me
</label>
<span class="psw">Forgot Password?</span>
<button onclick="getLoginInfo()" type="submit">Login</button>
</div>
</form>
</div>
<div class="col"></div>
</div>
</body>
</html>
I have fixed the issue by wrapping the eventlistener inside a function that runs when the window loads
// array of objects to store adminstrators data
var usersObj =[
{
username: "karim",
password: "karim2019"
},
{
username: "nourhan",
password: "noura2019"
},
{
username: "nariman",
password: "nariman2019"
}
]
// function to authenticate login information and proceed to the next page
function getLoginInfo()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(i = 0; i < usersObj.length; i++)
{
if(username == usersObj[i].username && password == usersObj[i].password)
{
alert("Login successful..");
document.getElementById("loginf").action = "dashboard.html";
return
}
}
alert("Username or password is incorrect!");
document.getElementById("loginf").action = "login.htm";
}
window.onload=function()
{
var input = this.document.getElementById("password");
var text = this.document.getElementById("text");
input.addEventListener("keyup", function(event)
{
if(event.getModifierState("CapsLock"))
{
text.style.display = "block";
}
else
{
text.style.display = "none";
}
});
};

Filtering directive in Angular.js

I'm trying to develop a single web application which is a blog, displaying posts. They are included in a template by the ng-repeat directive:
<div class="post" data-ng-repeat="post in postList ">
<div class="date">published: {{post.published_at | date:'dd-MM-yyyy, HH:mm'}}</div>
<a class="btn btn-default" data-ng-click="editPost(post)"><span class="glyphicon glyphicon-pencil"></span></a>
<a class="btn btn-default" data-ng-click="deletePost(post)"><span class="glyphicon glyphicon-remove"></span></a>
<h1>{{post.title}}</h1>
<p>{{post.text}}</p>
</div>
</div>
They have fields, such as title, text and publishing date, defined in the controller. I'd like to filter them by various criteria. For this purpose, I tried to implement my own custom filter (so that I can filter by more than 1 field):
angular.module("blog").
filter('bytitle', function() {
return function(posts, title) {
var out = [];
// Filter logic here, adding matches to the out var.
var i;
for(i = 0; i < posts.length; i++){
if(posts[i].title.indexOf(title) >=0){
out.push(posts[i]);
}
}
return out;
}
});
however, if I run the javascript console, I get the following error, caused only by the presence of the code above:
Argument 'postController' is not a function, got undefined
I'm new to angular, and I'm not really sure what this means. Any ideas?
The entire source code: http://plnkr.co/edit/suATcx8dQXZqcmmwlc0b?p=catalogue
Edit 2: The problem is partially solved. I added this filter functionality:
<div class="post" data-ng-repeat="post in postList | bytitle : filterTerm">
but something goes wrong while running the script:
TypeError: Cannot read property 'length' of undefined
It occurs at line 7 (the one with posts.length).
in you file with filters instead angular.module("blog", []) you need angular.module("blog").
in first case - you create module in second - get.
see doc:
When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.
sidenote: in plunker you have wrong reference to js files
You have error with length property, because before loading posts by ajax, you not init this variables, so in filter passed undefined.
You can modify your filter like
angular.module("blog").
filter('bytitle', function() {
return function(posts, title) {
var out = [];
//if not pass posts - return empty
if(!posts) return out;
//if not pass title, or it empty - return same collection
if(!title) return posts;
// Filter logic here, adding matches to the out var.
var i;
for (i = 0; i < posts.length; i++) {
if (posts[i].title.indexOf(title) >= 0) {
out.push(posts[i]);
}
}
return out;
}
});
var app = angular.module("blog", []);
app.controller("postController", function($scope, $http, $timeout) {
var path = 'http://private-79b25-blogtt.apiary-mock.com';
$scope.titleFilter = "";
$scope.contentFilter = "";
$http.get(path + '/posts')
.success(function(data, status, headers, config) {
$timeout(function() {
$scope.postList = data;
});
})
.error(function(data, status, headers, config) {
console.log("error getting " + status);
});
$scope.form_header = "New post";
$scope.addPost = function() {
var post = {
title: $scope.title,
text: $scope.text,
published_at: new Date()
};
$http.post(path + '/posts', post)
.success(function(data, status, headers, config) {
$scope.postList.push(post);
})
.error(function(data, status, headers, config) {
console.log("error posting " + status);
});
$scope.title = "";
$scope.text = "";
};
$scope.deletePost = function(post) {
var del = confirm("Are you sure you want to delete or modify this post?");
if (del) {
var i = $scope.postList.indexOf(post);
$scope.postList.splice(i, 1);
}
};
var backupPostContent;
$scope.editPost = function(post) {
$scope.deletePost(post);
$scope.form_header = "Edit post";
$scope.title = post.title;
$scope.text = post.text;
backupPostContent = post;
};
$scope.cancelEdit = function() {
$http.post(path + '/posts', backupPostContent)
.success(function(data, status, headers, config) {
$scope.postList.push(backupPostContent);
$scope.form_header = "New post";
})
.error(function(data, status, headers, config) {
console.log("error posting " + status);
});
$scope.title = "";
$scope.text = "";
};
$scope.filter = function(term) {
}
});
angular.module("blog").
filter('bytitle', function() {
return function(posts, title) {
var out = [];
if(!posts) return out;
if(!title) return posts;
// Filter logic here, adding matches to the out var.
var i;
for (i = 0; i < posts.length; i++) {
if (posts[i].title.indexOf(title) >= 0) {
out.push(posts[i]);
}
}
return out;
}
});
#wrap {
width: 600px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
}
body {
padding: 0px 15px;
}
.row-centered {
text-align: right;
}
.page-header {
background-color: #cb892c;
margin-top: 0;
padding: 20px 20px 20px 40px;
}
.page-header h1,
.page-header h1 a,
.page-header h1 a:visited,
.page-header h1 a:active {
color: #ffffff;
font-size: 36pt;
text-decoration: none;
}
.content {
margin-left: 40px;
}
h1,
h2,
h3,
h4 {
font-family: Helvetica, sans-serif;
}
.date {
float: right;
color: #828282;
}
.save {
float: right;
}
.post-form textarea,
.post-form input {
width: 60%;
}
.top-menu,
.top-menu:hover,
.top-menu:visited {
color: #ffffff;
float: right;
font-size: 26pt;
margin-right: 20px;
}
.post {
margin-bottom: 70px;
}
.post h1 a,
.post h1 a:visited {
color: #000000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="blog" ng-controller="postController">
<div id="wrap">
<div id="left_col">
<h3> Search </h3>
<p>
<input data-ng-model="filterTerm" />
</p>
</div>
<div id="right_col">
<div id="wrap">
<div id="left_col">
<input type="checkbox" value="topic" id="title" ng-model="titleFilter" />In topics
<br>
<input type="checkbox" value="content" id="content" />In contents
<br>
<input type="checkbox" value="content" id="content" />In tags
<br>Between
<input type="text" type="text" class="datepicker" />
</div>
<div id="right_col">
<br>
<br>
<br>and
<input type="text" type="text" class="datepicker" />
<br/>
</div>
</div>
</div>
</div>
<div class="content container" style="padding-top: 50px">
<div class="row">
<div class="col-md-8 col-centered">
<div class="post" data-ng-repeat="post in postList | bytitle : filterTerm ">
<div class="date">published: {{post.published_at | date:'dd-MM-yyyy, HH:mm'}}</div>
<a class="btn btn-default" data-ng-click="editPost(post)"><span class="glyphicon glyphicon-pencil"></span></a>
<a class="btn btn-default" data-ng-click="deletePost(post)"><span class="glyphicon glyphicon-remove"></span></a>
<h1>{{post.title}}</h1>
<p>{{post.text}}</p>
</div>
</div>
<div class="col-md-4 col-centered">
<h1>New post</h1>
<form class="post-form">
<h4>Title:</h4>
<p>
<input type="text" name="title" data-ng-model="title">
</p>
<h4>Text:</h4>
<p>
<textarea name="text" data-ng-model="text"></textarea>
</p>
<button type="submit" class="save btn btn-default" ng-click="addPost()">Save</button>
<button type="reset" class="btn btn-default">Clear</button>
<button type="button" class="btn btn-default" ng-click="cancelEdit()">Cancel edit</button>
</form>
</div>
</div>
</div>
</div>
EDIT
I didn't see the answer from #grundy before making my comments or edits, so it should be accepted as the answer, but I wanted to point out two things:
Working Plunker
My preferred approach is to use the angular.isDefined / angular.isArray:
angular.module("blog").
filter('bytitle', function() {
return function(posts, title) {
if(angular.isDefined(title) && angular.isArray(posts)) {
var out = [];
// Filter logic here, adding matches to the out var.
var i;
for(i = 0; i < posts.length; i++){
if(posts[i].title.indexOf(title) >=0){
out.push(posts[i]);
}
}
return out;
} else {
return posts;
}
}
});
Second, I just wanted to point out that while writing your own filters is sometimes necessary and certainly a great skill to master, the easiest way to filter on a single property is to use the built in filter filter by adding the property to the model value that you want to search on:
<input data-ng-model="filterTerm.title" />
<input data-ng-model="filterTerm.text" />
and then in your repeat add the filter using just the object name as follows:
<div class="post" data-ng-repeat="post in postList | filter: filterTerm ">
You can then use the same filter for multiple properties.

Categories