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.
Related
How do I make a modal visible with javascript? I don't want to do it using jquery. i just want it with javascript. And I don't want it to open when I click a button. I want it to be opened as a result of some operations in javascript. I made it with modal bootstrap. my codes are below.
html code:
<!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 href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="modal fade" tabindex="-1" id="sonucModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Test Durumu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="durum"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Çıkış</button>
<button type="button" class="btn btn-primary">2. Aşamaya Geç</button>
</div>
</div>
</div>
</div>
<div class="container" style="height: 100vh;">
<div class="row" style="height: 100vh;">
<div class="col-md-12 d-flex justify-content-center" style="height: 400px;">
<div class="card" style="width: 25rem; margin-top:20vh; ">
<div class="card-body" style="text-align: center;">
<h5 class="card-title text-primary">Soru</h5>
<span class="text-black-50 fs-5" id="soru"></span>
<input class="w-100 form-control mt-4" type="text" id="cevap"/>
<button class="btn btn-outline-primary mt-4 w-100" id="ok">Tamam</button>
</div>
<ul class="list-group list-group-flush">
<li id="anaCan" class="list-group-item fw-bold">Kalan Can: <span id="can"></span></li>
</ul>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
javascript code:
var turkceCumleler = [
"Merhaba",
"İyi Sabahlar",
"İyi Günler",
"İyi Akşamlar",
"İyi Geceler",
"Tekrar Görüşmek Üzere(Yüz yüze)",
"Tekrar Görüşmek Üzere(Tel.)",
"Yakında Görüşürüz",
"Güle Güle"
];
var almancaCumleler = [
"hallo",
"guten morgen",
"guten tag",
"guten abend",
"gute nacht",
"auf wiedersehen",
"auf wiederhögen",
"bis bald",
"tschüss"
]
var sayilar = [];
var healt = 3;
const getQuestion = () =>{
document.getElementById('can').textContent=healt;
let rastgele = Math.floor(Math.random()*turkceCumleler.length);
if(sayilar.indexOf(rastgele) === -1){
sayilar.push(rastgele)
document.getElementById('soru').textContent = turkceCumleler[rastgele];
document.getElementById('cevap').value = ""
}else{
getQuestion();
}
if(sayilar.length === turkceCumleler.length){
//here i want modal to open
}
}
const compareQuestionAnswer = () =>{
if(document.getElementById('cevap').value === ''){
alert("boş geçilemez")
}else{
let deger = almancaCumleler.indexOf(document.getElementById('cevap').value.toLowerCase());
if(deger === -1){
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}else{
let deger1 = turkceCumleler.indexOf(document.getElementById('soru').textContent);
if(deger === deger1){
getQuestion();
}else{
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}
}
}
}
window.onload = getQuestion;
document.getElementById('ok').addEventListener('click',compareQuestionAnswer);
document.getElementById('anaCan').style.color='green';
Bootstrap depends on jQuery, and you're already including jQuery in your code.
But if you want to create a modal without Bootstrap and jQuery, you can do so with CSS and JavaScript. Use an event listener to listen for whatever JavaScript event you desire, then show the modal when that event occurs.
Here is a simple example:
// Show the modal when you hover over the red box
trigger.onmouseover = () => {
modal.style.display = "block";
}
// Hide the modal when you click the close button
document.getElementsByClassName("close")[0].onclick = () => {
modal.style.display = "none";
}
// Hide the modal if you click outside of the modal area
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}
#trigger {
height: 100px;
width: 100px;
background-color: red;
}
.modal {
display: none; /* Hidden Initially */
position: fixed;
z-index: 1; /* Higher Z-Index To Sit On Top */
left: 0;
top: 0;
width: 100%; /* Full Width */
height: 100%; /* Full Height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div id="modal" class="modal">
<!-- Modal Content -->
<div class="modal-content">
<span class="close">x</span>
<p>Modal content here</p>
</div>
</div>
<div id="trigger">
Move mouse into this box to trigger modal.
</div>
You just need to declare a new modal object, like:
const sonucModal= document.getElementById('sonucModal');
const modalEl = new bootstrap.Modal(sonucModal);
and then call it like this whenever you need to open it:
modalEl.show();
Here is a JSFiddle for reference, the modal opens automatically after 2 seconds.
To start off I'm terrible at Js and super new at it. I'm trying to make a random image pop up when the site goes to a 404. I can't tell if my website is actually running the code or not because console.log wasn't working. Because of that I took all my CSS and js and put it all into the same HTML file to see if that was the problem (it wasn't) Any help is much appreciated :)
HTML:
<html>
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<div id="getMeme()"></div>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
document.getElementById("result").onload = '<img src="' + meme[pp] + '" />';
}
</script>
</html>
Using your code, you would need to ensure the function getMeme is called/invoked. Furthermore, you would need to update the function to modify the innerHTML of the element with id result instead of assigning to it's event handler onload.
See demo below:
I've included a console.log for debugging purposes on stackoverflow as images shared in the question are not available.
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<span id="result"></span>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
console.log("chose meme",meme[pp]); //line included for debugging purposes on stackoverflow as images shared in question are not available
//update `innerHTML` of target element
document.getElementById("result").innerHTML = '<img src="' + meme[pp] + '" />';
}
//call function to getMeme at the end of the page
getMeme();
</script>
</body>
</html>
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
I am not an expert in HTML, CSS, or JavaScript, but I have this website that needs to be responsive on all devices. However, it does not seem like it is working for some reason and instead creates major gaps of white space when I view the website on a mobile web browser:
Here is the code for it:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>untitled document</title>
<style media="screen">
body {
background-color: #f0f0f0;
font: 1em verdana, arial, helvetica, sans-serif;
line-height: 0px;
}
h1,h2 {
font-size: 2em;
color: #f00;
text-align: center;
text-shadow: 0 0 0.06em #000,0 0 0.12em #000;
}
.af-textWrap {
display: block;
text-align: center;
color: #b7b7b7;
}
.af-element {
text-align: center;
}
#awf_field-90534028,
#awf_field-90534029 {
display: block;
width: 98%;
max-width: 28.125em;
margin: auto;
text-align: left;
}
.image {
display: block;
width: 98%;
max-width: 30em;
height: auto;
margin: auto;
}
</style>
</head>
<body>
<div id="worked"></div>
<script src="https://fast.wistia.com/embed/medias/cj7247tp29.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_cj7247tp29 videoFoam=true" style="height:100%;width:100%"> </div></div></div>
<h1>Offer Ends In:</h1>
<h2 id="time"></h2>
<!-- AWeber Web Form Generator 3.0.1 -->
<form class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" method="post">
<input name="meta_web_form_id" type="hidden" value="604218668">
<input name="meta_split_id" type="hidden" value="">
<input name="listname" type="hidden" value="awlist4661276">
<input id="redirect_56ab2ff33416d920a3c24dc4d8e140f4" name="redirect" type="hidden" value="http://bloggingnetworkonline.com/InternetMarketing/?page_id=133&preview=true">
<input name="meta_adtracking" type="hidden" value="My_Web_Form">
<input name="meta_message" type="hidden" value="1">
<input name="meta_required" type="hidden" value="name,email">
<input name="meta_tooltip" type="hidden" value="name||First Name...,,email||Best Email...">
<div id="af-form-604218668" class="af-form">
<div id="af-body-604218668" class="af-body af-standards">
<div class="af-element">
<label class="previewLabel" for="awf_field-90534028"></label>
<div class="af-textWrap">
<input id="awf_field-90534028" class="text" tabindex="500" name="name" type="text" placeholder="First Name...">
</div>
</div>
<div class="af-element">
<label class="previewLabel" for="awf_field-90534029"></label>
<div class="af-textWrap">
<input id="awf_field-90534029" class="text" tabindex="500" name="email" type="text" placeholder="Best Email...">
</div>
</div>
<div class="af-element buttonContainer">
<input id="af-submit-image-604218668" class="image" tabindex="502" alt="Submit Form" name="submit" src="https://hostedimages-cdn.aweber-static.com/MTE0ODQyNQ==/original/d316599087b84f9498e3854009bdad52.png" type="image"/>
</div>
<div class="af-element privacyPolicy">
<p><strong>I respect your <a title="Privacy Policy" href="https://www.aweber.com/permission.htm" target="_blank" rel="nofollow">email privacy</a></strong></p>
<div class="af-clear"> </div>
</div>
</div>
</div>
<div style="display: none;"><img src="https://forms.aweber.com/form/displays.htm?id=bAwsTIwcbGwc" alt="">
</div>
</form>
<!-- /AWeber Web Form Generator 3.0.1 -->
<script>
(function() {
'use strict';
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = '0' + min + 'm';
var min2 = min + 'm';
var sec1 = '0' + sec + 's';
var sec2 = sec + 's';
var col = ':';
document.getElementById('time').textContent = (min < 10 ? min1 : min2) + col + (sec < 10 ? sec1 : sec2);
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
}());
</script>
</body>
</html>
Looks like your iframe is injected by JavaScript so I personally suggest adding a setInterval() to your code to monitor the iframe element. Once the iframe element is available, get the body in the iframe and set it's margin to 0.
$(function() {
$('#test').append('<iframe src="http://www.w3schools.com"></iframe>');
var timer = setInterval(function() {
$('iframe').load( function() {
$('iframe').contents().find("head").append($("<style type='text/css'>body{margin:0;}</style>"));
clearInterval( timer ); // Clear the interval
});
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
My Classic ASP cart page uses divs for a quantity selector within a form:
<form action="/update-cart/" method="post">
<div class="quantity-selector detail-info-entry">
<div class="detail-info-entry-title">Quantity</div>
<div class="entry number-minus"> </div>
<div class="entry number">1</div>
<div class="entry number-plus"> </div>
</div>
</div>
</form>
when - or + is clicked the 1 will update as expected. the code to do this is this:
$('.number-plus').on('click', function(){
var divUpd = $(this).parent().find('.number'), newVal = parseInt(divUpd.text(), 10)+1;
divUpd.text(newVal);
});
$('.number-minus').on('click', function(){
var divUpd = $(this).parent().find('.number'), newVal = parseInt(divUpd.text(), 10)-1;
if(newVal>=1) divUpd.text(newVal);
});
What is the easiest way to post the content of the div with class "number" above when a form is submitted. Do i use:
<input type="hidden" id="Num" name="Num" value="" />
Or another way. Either way, how can this be done easily as I cannot get the variable "newVal" to populate the hidden field.
Thanks
This demo has 2 features of note.
The following are done with HTML and inline JS (e.g. onchange='...)
<input>s .number-minus and number-plus
<output> .number displays the sum of .number-minus and .number-plus
As requested, the sum of .number-minus and .number-plus is stored in a <input [hidden]> named .secret. This value was derived from <output> value by using jQuery (overkill IMO). `
$(function() {
$('#pos, #neg').on('change', function(event) {
var cnt = $('#counter').val();
$('#secret').val(cnt);
console.log('Secret: ' + secret.value);
});
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript/jquery onChange function for div.text to update form hidden field value</title>
<meta name="description" content="SO33312004">
<style>
.detail-info-entry-title,
#pos,
#neg {
font-variant: small-caps;
}
.entry {
padding: 3px;
margin: 0 5px;
width: 48px;
line-height: 1.6;
border: 2px solid #00E;
border-radius: 8px;
display: table-cell;
}
#counter {
font-weight: 900;
margin: auto;
display: table-cell;
height: 24px;
}
#form33312004 {
color: #0CF;
background: hsla(180, 100%, 10%, 1);
width: 33%;
height: 30%;
text-align: center;
vertical-align: middle;
display: table-row;
}
.field {
width: 50px;
display: table-cell;
}
footer {
font-size: .75em;
text-align: center;
}
</style>
</head>
<!--http://stackoverflow.com/questions/33312004/javascript-jquery-onchange-function-for-div-text-to-update-form-hidden-field-val-->
<body>
<form id="form33312004" submit="return false" oninput="counter.value = parseInt(pos.value, 10) - parseInt(neg.value, 10)">
<fieldset class="quantity-selector detail-info-entry">
<legend class="detail-info-entry-title">Quantity</legend>
<div class="field">
<input type="number" id="pos" min="0" max="999" step="any" value="0" class="entry number-plus">
<label for="pos">Positive</label>
</div>
<output for='pos neg' id="counter" name="counter" class="entry number">0</output>
<div class="field">
<input type="number" id="neg" min="0" max="999" step="any" value="0" class="entry number-minus">
<label for="neg">Negative</label>
</div>
</fieldset>
<input id="secret" type="hidden">
</form>
<div class="field">
<footer>Observe the hidden input's value thru
<br/>the console. (<b>F12</b> then the <b>Console</b> tab).</footer>
<script sr="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
</body>
</html>
With pure JS:
document.getElementById("Num").value = < variable name >
With jQuery(not 100% sure)
$("Num").value(< variable name>)
So I solved the problem myself.
I added the following line:
$("#Num").val(newVal);
To both the jquery functions for the + and - divs as follows:
$('.number-plus').on('click', function(){
var divUpd = $(this).parent().find('.number'), newVal = parseInt(divUpd.text(), 10)+1;
divUpd.text(newVal);
$("#Num").val(newVal);
});
$('.number-minus').on('click', function(){
var divUpd = $(this).parent().find('.number'), newVal = parseInt(divUpd.text(), 10)-1;
if(newVal>=1) divUpd.text(newVal);
$("#Num").val(newVal);
});
I am sure I had tried this but after thought I may have omitted the $ at the beginning. Always something simple in the end