So i have the following 2 checkboxes on my page on small script attached to it which is designed to hide the billing section.
<script>
function myFunction2() {
var x = document.getElementById("billing_info");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I'm using the below script to try and uncheck the checkboxes
<script>
$(document).ready( function a()
{
if ( $('#sameAsBilling').is(':checked'))
{
$('#check2').attr('checked', false);
}
});
</script>
<div class="header">
<h3 class="checkout-headers">STEP 3 - Billing Information </h3>
<!--START: sameAsBilling1-->
<!--value="ON"-->
<div class="sameAsBilling1">
<input type="checkbox" name="sameAsBilling" id="sameAsBilling" onclick="showHideShipping();check_address('');"/>
<label for="sameAsBilling">Same as Delivery Address</label>
<div class="clear"></div>
</div>
<div class="differentBilling">
<input type="checkbox" class="example" id="check2" onclick="myFunction2()"; return false;>Different Billing Address?</div>
<!--END: sameAsBilling1-->
<div class="clear"></div>
</div>
My problem is someone as buried the following code in a javascript file which is what transfers the delivery details onto the billing details if the specific checkbox is ticked.
function showHideShipping() {
if (document.billing.sameAsBilling.checked) {
add_overlay("billing_info", 0);
if (get_Element('billing_firstname').value != get_Element('shipping_firstname').value) {
get_Element('billing_firstname').value = get_Element('shipping_firstname').value;
get_Element('billing_lastname').value = get_Element('shipping_lastname').value;
get_Element('billing_company').value = get_Element('shipping_company').value;
get_Element('billing_phone').value = get_Element('shipping_phone').value;
get_Element('billing_address').value = get_Element('shipping_address').value;
get_Element('billing_address2').value = get_Element('shipping_address2').value;
get_Element('billing_city').value = get_Element('shipping_city').value;
get_Element('billing_zip').value = get_Element('shipping_zip').value;
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
} else {
remove_overlay("billing_info");
get_Element('billing_firstname').value = '';
get_Element('billing_lastname').value = '';
get_Element('billing_company').value = '';
get_Element('billing_phone').value = '';
get_Element('billing_address').value = '';
get_Element('billing_address2').value = '';
get_Element('billing_city').value = '';
get_Element('billing_zip').value = '';
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
}
You're missing an else. So the code that hides the billing info and copies the shipping info to it is executed all the time, regardless of the state of the checkbox.
if (document.billing.sameAsBilling.checked) {
add_overlay("billing_info", 0);
get_Element('billing_firstname').value = '';
get_Element('billing_lastname').value = '';
get_Element('billing_company').value = '';
get_Element('billing_phone').value = '';
get_Element('billing_address').value = '';
get_Element('billing_address2').value = '';
get_Element('billing_city').value = '';
get_Element('billing_zip').value = '';
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
} else {
remove_overlay("billing_info");
if (get_Element('billing_firstname').value != get_Element('shipping_firstname').value) {
get_Element('billing_firstname').value = get_Element('shipping_firstname').value;
get_Element('billing_lastname').value = get_Element('shipping_lastname').value;
get_Element('billing_company').value = get_Element('shipping_company').value;
get_Element('billing_phone').value = get_Element('shipping_phone').value;
get_Element('billing_address').value = get_Element('shipping_address').value;
get_Element('billing_address2').value = get_Element('shipping_address2').value;
get_Element('billing_city').value = get_Element('shipping_city').value;
get_Element('billing_zip').value = get_Element('shipping_zip').value;
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
}
Related
I have a webapp that retrieves from a Google sheet an array of values to dynamically create a table so if the array retrieved has four items, then the table has four rows, and so on.Each row has as first column item a toggle to disables the other columns' input fields for that row.
It looks like this:
I initially created everything statically, just to get it working first, with five sample rows, and got every thing working, the toggle worked and disabled and cleared content, etc. However, as I wrote in the part to dynamically create the table rows and the event listeners for each toggle, the toggle stopped responding, even though the function for each is named correctly according to the dynamically created event listeners.
These rows are done in the javascript for the page, using this statement:
document.addEventListener('DOMContentLoaded', setup_ui);
After creating the table rows and before the end of the setup_ui function, I create the event listeners for each toggle.
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
You see, at this point, I do have the rows created, they show up, all appears well. And yet, if I do
alert(document.getElementById("domain1"))
It doesn't find it... even though its in front of me and I can right click on the page, go into dev tools and see it there.
The code for the function handling the toggle is there below in the file, here's the first function for the first toggle.
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
How can I not only create those table rows dynamically, as I have done here, but also have the event listeners I create dynamically actually work with the functions that are later down in that js file?
I will have to eventually have the functions to handle the toggles created dynamically as well and I have no clue at this point.
To replicate this you'd need yourself a new AppScript project webapp.
Here's the code for my html and js.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?!= include('menu-css'); ?>
<?!= include('users-css'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body class="body">
<?!= include('menu'); ?>
<div class="user-create-form">
<h5 id="title"> Create User</h5> </br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name">
</div>
<div class="col-sm">
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email">
</div>
</div>
</br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position">
</div>
<div class="col-sm">
<select class="form-select" aria-label="Default select example" id="role">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</div>
</div>
</br>
<div class="toggles">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="alldomains">
<label class="form-check-label" for="flexSwitchCheckDefault">All Domains</label>
</div>
<table class="table w-auto">
<thead>
<tr>
<th scope="col" class="col col-auto">
Domains
</th>
<th scope="col">
First name
</th>
<th scope="col">
Last name
</th>
<th scope="col">
Email
</th>
<th scope="col">
Phone number
</th>
<th scope="col">
company position
</th>
<th scope="col">
Role
</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<?!= include('menu-js'); ?>
<?!= include('users-js'); ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
And now the Javascript:
<script>
document.addEventListener('DOMContentLoaded', setup_ui);
function setup_ui(){
var count = 4;
document.getElementById("title").innerHTML = `Create a User across any number of your ${count} domains`;
create_table();
document.getElementById("alldomains").click();
document.getElementById("alldomains").click();
}
google.script.run.withSuccessHandler(create_table).get_domains_names();
function create_table(domains_names){
var domains_count = domains_names.length;
var row_html;
if(domains_count > 0){
var table = document.getElementById("tbody");
var table_body = table.innerHTML;
for(var i = 0; i < domains_count; i++){
let domain = domains_names[i];
let number = i+1;
row_html = `
<tr>
<td>
<div class="form-check form-switch form-check-inline">
<input class="form-check-input" type="checkbox" id="domain${number}">
<label class="form-check-label" for="flexSwitchCheckDefault">${domain}</label>
</div>
<td>
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position_domain${number}">
</td>
<td>
<select class="form-select" aria-label="Default select example" id="role_domain${number}">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</td>
</tr>
`;
let row = document.createElement("tr");
row.innerHTML = row_html;
tbody.appendChild(row);
}
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
// Next we need to create the functions to provide the functionality for each toggles
}else{ // no domains (they need to add the domains)
}
}
document.getElementById("alldomains").addEventListener("click",applyAllDomains);
function applyAllDomains(){
document.getElementById("domain1").click();
document.getElementById("domain2").click();
document.getElementById("domain3").click();
document.getElementById("domain4").click();
document.getElementById("domain5").click();
switch_for_dom1();
switch_for_dom2();
switch_for_dom3();
switch_for_dom4();
switch_for_dom5();
}
document.getElementById("first_name").addEventListener("input",map_first_name);
document.getElementById("last_name").addEventListener("input",map_last_name);
document.getElementById("email").addEventListener("input",map_email);
document.getElementById("phone").addEventListener("input",map_phone);
document.getElementById("position").addEventListener("input",map_position);
document.getElementById("role").addEventListener("input",map_role);
function map_first_name(){
alert("here");
var fn = document.getElementById("first_name").value;
if(document.getElementById("first_name_domain1").disabled == false){
document.getElementById("first_name_domain1").value = fn;
}
if(document.getElementById("first_name_domain2").disabled == false){
document.getElementById("first_name_domain2").value = fn;
}
if(document.getElementById("first_name_domain3").disabled == false){
document.getElementById("first_name_domain3").value = fn;
}
if(document.getElementById("first_name_domain4").disabled == false){
document.getElementById("first_name_domain4").value = fn;
}
if(document.getElementById("first_name_domain5").disabled == false){
document.getElementById("first_name_domain5").value = fn;
}
}
function map_last_name(){
var fn = document.getElementById("last_name").value;
if(document.getElementById("last_name_domain1").disabled == false){
document.getElementById("last_name_domain1").value = fn;
}
if(document.getElementById("last_name_domain2").disabled == false){
document.getElementById("last_name_domain2").value = fn;
}
if(document.getElementById("last_name_domain3").disabled == false){
document.getElementById("last_name_domain3").value = fn;
}
if(document.getElementById("last_name_domain4").disabled == false){
document.getElementById("last_name_domain4").value = fn;
}
if(document.getElementById("last_name_domain5").disabled == false){
document.getElementById("last_name_domain5").value = fn;
}
}
function map_email(){
var fn = document.getElementById("email").value;
if(document.getElementById("email_domain1").disabled == false){
document.getElementById("email_domain1").value = fn;
}
if(document.getElementById("email_domain2").disabled == false){
document.getElementById("email_domain2").value = fn;
}
if(document.getElementById("email_domain3").disabled == false){
document.getElementById("email_domain3").value = fn;
}
if(document.getElementById("email_domain4").disabled == false){
document.getElementById("email_domain4").value = fn;
}
if(document.getElementById("email_domain5").disabled == false){
document.getElementById("email_domain5").value = fn;
}
}
function map_phone(){
var fn = document.getElementById("phone").value;
if(document.getElementById("phone_domain1").disabled == false){
document.getElementById("phone_domain1").value = fn;
}
if(document.getElementById("phone_domain2").disabled == false){
document.getElementById("phone_domain2").value = fn;
}
if(document.getElementById("phone_domain3").disabled == false){
document.getElementById("phone_domain3").value = fn;
}
if(document.getElementById("phone_domain4").disabled == false){
document.getElementById("phone_domain4").value = fn;
}
if(document.getElementById("phone_domain5").disabled == false){
document.getElementById("phone_domain5").value = fn;
}
}
function map_position(){
var fn = document.getElementById("position").value;
if(document.getElementById("position_domain1").disabled == false){
document.getElementById("position_domain1").value = fn;
}
if(document.getElementById("position_domain2").disabled == false){
document.getElementById("position_domain2").value = fn;
}
if(document.getElementById("position_domain3").disabled == false){
document.getElementById("position_domain3").value = fn;
}
if(document.getElementById("position_domain4").disabled == false){
document.getElementById("position_domain4").value = fn;
}
if(document.getElementById("position_domain5").disabled == false){
document.getElementById("position_domain5").value = fn;
}
}
function map_role(){
var fn = document.getElementById("role").value;
if(document.getElementById("role_domain1").disabled == false){
document.getElementById("role_domain1").value = fn;
}
if(document.getElementById("role_domain2").disabled == false){
document.getElementById("role_domain2").value = fn;
}
if(document.getElementById("role_domain3").disabled == false){
document.getElementById("role_domain3").value = fn;
}
if(document.getElementById("role_domain4").disabled == false){
document.getElementById("role_domain4").value = fn;
}
if(document.getElementById("role_domain5").disabled == false){
document.getElementById("role_domain5").value = fn;
}
}
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
function switch_for_dom2(){
let check = document.getElementById("domain2");
if(check.checked == true){
document.getElementById("first_name_domain2").disabled = false;
document.getElementById("last_name_domain2").disabled = false;
document.getElementById("email_domain2").disabled = false;
document.getElementById("phone_domain2").disabled = false;
document.getElementById("position_domain2").disabled = false;
document.getElementById("role_domain2").disabled = false;
}else{
document.getElementById("first_name_domain2").disabled = true;
document.getElementById("last_name_domain2").disabled = true;
document.getElementById("email_domain2").disabled = true;
document.getElementById("phone_domain2").disabled = true;
document.getElementById("position_domain2").disabled = true;
document.getElementById("role_domain2").disabled = true;
document.getElementById("first_name_domain2").value = "";
document.getElementById("last_name_domain2").value = "";
document.getElementById("email_domain2").value = "";
document.getElementById("phone_domain2").value = "";
document.getElementById("position_domain2").value = "";
document.getElementById("role_domain2").value = "Role";
}
}
function switch_for_dom3(){
let check = document.getElementById("domain3");
if(check.checked == true){
document.getElementById("first_name_domain3").disabled = false;
document.getElementById("last_name_domain3").disabled = false;
document.getElementById("email_domain3").disabled = false;
document.getElementById("phone_domain3").disabled = false;
document.getElementById("position_domain3").disabled = false;
document.getElementById("role_domain3").disabled = false;
}else{
document.getElementById("first_name_domain3").disabled = true;
document.getElementById("last_name_domain3").disabled = true;
document.getElementById("email_domain3").disabled = true;
document.getElementById("phone_domain3").disabled = true;
document.getElementById("position_domain3").disabled = true;
document.getElementById("role_domain3").disabled = true;
document.getElementById("first_name_domain3").value = "";
document.getElementById("last_name_domain3").value = "";
document.getElementById("email_domain3").value = "";
document.getElementById("phone_domain3").value = "";
document.getElementById("position_domain3").value = "";
document.getElementById("role_domain3").value = "Role";
}
}
function switch_for_dom4(){
let check = document.getElementById("domain4");
if(check.checked == true){
document.getElementById("first_name_domain4").disabled = false;
document.getElementById("last_name_domain4").disabled = false;
document.getElementById("email_domain4").disabled = false;
document.getElementById("phone_domain4").disabled = false;
document.getElementById("position_domain4").disabled = false;
document.getElementById("role_domain4").disabled = false;
}else{
document.getElementById("first_name_domain4").disabled = true;
document.getElementById("last_name_domain4").disabled = true;
document.getElementById("email_domain4").disabled = true;
document.getElementById("phone_domain4").disabled = true;
document.getElementById("position_domain4").disabled = true;
document.getElementById("role_domain4").disabled = true;
document.getElementById("first_name_domain4").value = "";
document.getElementById("last_name_domain4").value = "";
document.getElementById("email_domain4").value = "";
document.getElementById("phone_domain4").value = "";
document.getElementById("position_domain4").value = "";
document.getElementById("role_domain4").value = "Role";
}
}
function switch_for_dom5(){
let check = document.getElementById("domain5");
if(check.checked == true){
document.getElementById("first_name_domain5").disabled = false;
document.getElementById("last_name_domain5").disabled = false;
document.getElementById("email_domain5").disabled = false;
document.getElementById("phone_domain5").disabled = false;
document.getElementById("position_domain5").disabled = false;
document.getElementById("role_domain5").disabled = false;
}else{
document.getElementById("first_name_domain5").disabled = true;
document.getElementById("last_name_domain5").disabled = true;
document.getElementById("email_domain5").disabled = true;
document.getElementById("phone_domain5").disabled = true;
document.getElementById("position_domain5").disabled = true;
document.getElementById("role_domain5").disabled = true;
document.getElementById("first_name_domain5").value = "";
document.getElementById("last_name_domain5").value = "";
document.getElementById("email_domain5").value = "";
document.getElementById("phone_domain5").value = "";
document.getElementById("position_domain5").value = "";
document.getElementById("role_domain5").value = "Role";
}
}
</script>
The problem is function_name is a string, rather than the reference to a function.
May I propose you do the following.
const switch_for_dom1 = function () { }
const switch_for_dom2 = function () { }
etc.
Then in
function create_table(domains_names){
.
.
.
let dom_functions = [switch_for_dom1,switch_for_dom2,....];
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = dom_functions[i];
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
}
I am working with program that will randomly choose who is making a Christmas gift to whom.
I've created an empty array. When you add a "player" it's pushing the name into two different arrays. Players[] and Players2[].
When you start a draw. The program writes the names of the Players[] on the left hand side and on the right side it writes the drawn names from Players2[].
Every Player from Players2[], after being drawn, is being deleted from the array so in the end we have an empty Players2[] array and full Players[] array.
The problem is: I can't make a working if statement that is checking if the person will not draw himself...
let Players = [];
let Players2 = [];
const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');
addBTN.addEventListener('click', function() {
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
console.log('error_empty_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Wpisz imię osoby!";
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Dodaj kolejną osobę.";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
});
refreshBTN.addEventListener('click', function() {
document.getElementById('warning').style.display = "block";
});
warningBTNyes.addEventListener('click', function() {
location.reload(true);
document.getElementById('addPLAYER').value = "";
});
warningBTNno.addEventListener('click', function() {
document.getElementById('warning').style.display = "none";
});
startBTN.addEventListener('click', function() {
drawLotsBTN.disabled = false;
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Zaczynasz losowanie!";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
document.getElementById('addPLAYER').disabled = true;
});
drawLotsBTN.addEventListener('click', function() {
for (let i = 0; i = Players2.length; i++) {
if (Players2.length > 0) {
randomPerson = Math.floor(Math.random() * Players2.length);
if (randomPerson != Players.indexOf(i)) {
console.log(Players2[randomPerson]);
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
Players2.splice(randomPerson, 1);
}
} else {
console.log('error_empty_array');
}
}
});
<div id="warning" class="warning">
<div class="warning-flex">
<h1>Wszelkie wpisane imiona zostaną usunięte</h1>
<div class="warning-buttons">
<button id="warning-button-yes" class="warning-button-yes">Tak</button>
<button id="warning-button-no" class="warning-button no">Nie</button>
</div>
</div>
</div>
<div class="lotteryContainer">
<div class="left">
<p>dodaj osobę</p>
<div class="addPerson">
<input required id="addPLAYER" type="text">
<button id="addBTN">+</button>
<p id="errorMSG"></p>
<div class="refresh">
<button id="refreshBTN">Od nowa</button>
<button id="startBTN">Start</button>
</div>
</div>
</div>
<div class="right">
<p>Uczestnicy</p>
<div class="tables">
<div class="tableLeft">
<p id=playersList></p>
</div>
<div class="tableRight">
<p id="playersList2"></p>
</div>
</div>
<button id="drawLotsBTN">Losuj</button>
</div>
</div>
<script src="app.js"></script>
Now if I understand what your program aims to do, there is a simple algorithm for it.
How I understand your goal:
You have a list of persons who are going to give presents to each other. (like in secret Santa). It is random who will give to who, but each person gives and receives one gift.
How to implement it (i'd normaly use maps, but I am guessing you are more comfortable with arrays):
players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffles array
gives_to = [...players]; // copy values of array
gives_to.push(gives_to.shift()); // let the first element be the last
Here the first player (players[0]) will give to gives_to[0] and the second to gives_to[1] etc.
I've created this JS script trying to use Trygve Ruud algorithm but it doesn't work like desired.
drawLotsBTN.addEventListener('click', function(){
if(Players.length > 0) {
console.log(Players)
Players.sort(function(a, b){
return 0.5 - Math.random();
});
for(let i = 0; i < Players.length; i++){
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
}
}
else{
console.log('error_empty_array');
}
});
I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>
I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})