hello I have problems with my zn javascript conditions
I have been looking for more than 3 days but it does not work well
here is what i want
1° retrieve the tick radio button
2° check the numbers enter
if the shipping methods are POSTE-COLIS-BELGIQUE_point or POSTE-ENVELLOPPE-belgium or MONDIAL-RELAY-BELGIQUE or POSTE-COLIS-BELGIQUE
if the postal code starts with 81 , 74 ,72 ,63 , 59 ,58 ,57 ,54 ,52 ,27
then we display an error message and we reset the imput postal code field to 0
IT WORKS
3°I want to check if the postal code is empty
if postal code is empty then error message
if the postal code is filled in, no message
IT DOES NOT WORK
4° I want to check that the postal code does not have a letter in the input field except for
MONDIAL-RELAY-PAYS-BAS or POSTE-ENVELLOPPE-PAYS-BAS
if the shipping method does not correspond to MONDIAL-RELAY-PAYS-BAS or POSTE-ENVELLOPPE-PAYS-BAS
the input field cannot accept letters
if letter in input field with a tick other than MONDIAL-RELAY-PAYS-BAS or POSTE-ENVELLOPPE-PAYS-BAS
then error message
IT DOES NOT WORK
$('input[name="choix_livraison"]').on('click', function() {
// console.log($(this).attr('data-nom'))
var livraison = $(this).attr('data-nom')
if (livraison === "POSTE-COLIS-BELGIQUE_point" || livraison === "POSTE-ENVELLOPPE-belgique" || livraison === "MONDIAL-RELAY-BELGIQUE" || livraison === "POSTE-COLIS-BELGIQUE") {
console.log(livraison);
//premiere fonction pour controler si pas numero interdit
var input = document.getElementById("cp").value;
console.log(input);
$("#cp").on("input", function() {
let cp = $(this).val();
//console.log(cp);
if ( cp === "81" || cp === "74" || cp === "72" || cp === "63" || cp === "59" || cp === "58" || cp === "57" || cp === "54" || cp === "52" || cp === "27") {
document.getElementById("mycp1").innerHTML = "<span style='background-color: #fffb11;color: red;font-weight: bold;'>Aucun code postal belge ne commence par " + cp + " </span>";
//document.getElementById("cp").style.borderColor= "crimson";
// document.getElementById("cp").style.borderWidth = "0.25em";
//document.getElementById('cache_container_mondial').style.display = 'none';
$('#cp').val('')
} else {
if (cp === null || cp === '') {
document.getElementById("mycp").innerHTML = "<sapn style='background-color: #fffb11;color: red;font-weight: bold;'>vous devez remplir votre cp </span>";
document.getElementById("mycp1").innerHTML = "";
document.getElementById("cp").style.borderColor = "crimson";
document.getElementById("cp").style.borderWidth = "0.25em";
} else {
document.getElementById("mycp").innerHTML = "";
document.getElementById("cp").style.borderColor = "";
document.getElementById("cp").style.borderWidth = "";
document.getElementById("mycp1").innerHTML = "";
}
}
})
}
})
//*********************************
// Ma deuxieme partie
//**************************************
$('input[name="choix_livraison"]').on('click', function() {
// console.log($(this).attr('data-nom'))
var livraison = $(this).attr('data-nom')
if (livraison !== 'MONDIAL-RELAY-PAYS-BAS' && livraison !== "POSTE-ENVELLOPPE-PAYS-BAS") {
console.log("autre pays que pays bas ",livraison);
//premiere fonction pour controler si pas numero interdit
// var inpute = document.getElementById("cp").value;
$("#cp").on("input", function() {
let cp = $(this).val();
console.log("autre pays que pays bas ",livraison);
//console.log("cp tout sauf hollande ",cp)
var cpvalidation = document.getElementById("cp").value;
if (isNaN(cpvalidation)) {
document.getElementById("mycp").innerHTML = "<sapn style='background-color: #fffb11;color: red;font-weight: bold;'>il ne peux y avoir que des chiffres</span>";
document.getElementById("cp").style.borderColor = "crimson";
document.getElementById("cp").style.borderWidth = "0.25em";
} else {
document.getElementById("mycp").innerHTML = "";
document.getElementById("cp").style.borderColor = "";
document.getElementById("cp").style.borderWidth = "";
}
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px; display: none;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison articleBtnposteinvisible" checked="checked" data-lang="de" data-nom="Ne sont pas encore choisi" value="" />
Par poste enveloppe (je ne suis pas responsable des pertes éventuelles) 1,10 euros
</div>
</div>
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison articleBtnposte" data-lang="de" data-nom="POSTE-ENVELLOPPE-belgique" value="1.10" id ="choix1" />
<span>Par poste enveloppe (je ne suis pas responsable des pertes éventuelles) 1,10 euros</span>
</div>
</div>
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison" data-nom="MONDIAL-RELAY-BELGIQUE" data-lang="be" value="3.00" /> Par Mondial Relay avec suivi du colis 3 euros
</div>
</div>
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison" data-nom="POSTE-COLIS-BELGIQUE" value="6.50" /> Par poste colis avec garanti a votre domicile 6.50 euros
</div>
</div>
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison" data-nom="POSTE-COLIS-BELGIQUE_point" data-lang="fr" value="5.50" /> Par poste dans un point d’enlèvement 5.50 euros
</div>
</div>
</div>
<p>
pour les payx bas
</p>
<div class="container">
<!-- debut pour le reste les pays-bas-->
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison" data-nom="POSTE-ENVELLOPPE-PAYS-BAS" value="2" data-lang="de" onclick="ouvreMaJolieAlertposte(event,' ');" /> Par poste
enveloppe (je ne suis pas responsable des pertes éventuelles) 2 euro
</div>
</div>
<div class="row" style="background: #ece9e7; margin-bottom: 10px; border-color: #000; border-style: solid; border-width: 5px;">
<div class="col-sm">
<input type="radio" name="choix_livraison" class="choix_livraison" data-nom="MONDIAL-RELAY-PAYS-BAS" data-lang="be" value="5.00" /> Par Mondial Relay avec suivi du colis 5 euros
</div>
</div>
</div>
<label for="cp">Code postal</label>
<input class="form-control" type="text" name="cp" value="" id="cp" required="required" />
<div id="mycp"></div>
<div id="mycp1"></div>
Related
I'm back with my form ....
My form validation runs well so now I try to load a confirmation modal after that my form was valided and submited, so that users just click "understood".
When I click on the submit button, my modal appear and disapear immediately, I think it's because, after that the form was submited, the window is refreshed.
I spend a whole day at this f**king things and I don't be able to fix it.
I don't understand something...
My question is simple, how can I load my modal after that my form was submited ??
My JS code :
function editNav() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
// DOM Elements
const modalbg = document.querySelector(".bground");
const modalBtn = document.querySelectorAll(".modal-btn");
const formData = document.querySelectorAll(".formData");
//VARIABLES
const xButton = document.querySelector(".close"); // Bouton croix
const subButton = document.querySelector(".button"); //Bouton submit
let firstName = document.querySelector("#firstName"); // Prénom
let lastName = document.querySelector("#lastName"); // Nom
let email = document.querySelector("#email"); //Email
let birthdate = document.querySelector("#birthdate"); //Date de naissance
let nbrTournaments = document.querySelector("#quantity"); //Nbr tournois
let myForm = document.getElementById("reserve");
//Formulaire complet
let emailError = document.querySelector(".mail-error"); //Erreur email
let firstNameError = document.querySelector('.firstname-error'); //Erreur prénom
let lastNameError = document.querySelector('.lastname-error'); //Erreur nom
let tournamentError = document.querySelector('.tournament-error'); //Erreur nbr tournois
let radioError = document.querySelector(".radio-button-error");//Erreur checkbox
let radioButton = document.forms[0].location;//Radio button
let birthdateError = document.querySelector(".birthdate-error");
let checkboxError = document.querySelector(".checkbox-error");
let checkbox = document.querySelector("#checkbox1");
//REGEXP
let emailRegExp = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let dateRegExp =/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
//MODAL
// launch modal event
modalBtn.forEach((btn) => btn.addEventListener("click", launchModal));
// launch modal form
function launchModal() {
modalbg.style.display = "block";
}
// close modal event
xButton.addEventListener("click", closeModal);
// close modal form
function closeModal() {
modalbg.style.display = "none";
}
//===================================================================================
//ThanksMODAL CONST
const thanksModalContainer = document.querySelector(".thanks-modal-container"); //ThanksMODAL container
const closeThanksModalBtn = document.querySelector(".thanks-modal-close-btn");
//Modal close button
closeThanksModalBtn.addEventListener("click", closeThanksModal);
// close thanks-modal FUNCTION
function closeThanksModal() {
thanksModalContainer.style.display = "none";
}
//launch thanks-modal EVENT
subButton.addEventListener("submit",launchThanksModal)
//launch thanks-modal FUNCTION
function launchThanksModal() {
thanksModalContainer.style.display = "block";
}
//======================================================================================
//VALIDATION FORMULAIRE
function validate() {
// Validation Prenom
if (firstName.value === "") {
firstNameError.innerHTML = "Votre prénom doit contenir 2 caractères ou plus.";
// return false;
}
// Validation Nom
if (lastName.value === "") {
lastNameError.innerHTML = "Votre nom doit contenir 2 caractères ou plus!";
// return false;
}
//Validation Mail
let testEmail = emailRegExp.test(email.value);
if ((testEmail === false) || (email.value === "")) {
emailError.innerHTML = "Veuillez saisir une adresse email valide.";
// return false;
}
//Validation Date de naissance
let testDate = dateRegExp.test(birthdate.value);
if (testDate === false) {
birthdateError.innerHTML = "Veuillez entrer votre date de naissance.";
// return false;
}
//Validation nombre de tournois
if (nbrTournaments.value === "") {
tournamentError.innerHTML = "Veuillez entrer un nombre";
// return false;
}
//Validation Radio Button
//Boucle vérifier
let valid = false;
for(let i = 0; i < radioButton.length; i++) {
if (radioButton[i].checked){
valid = true;
break;
}
}
if(valid) {
radioError.innerHTML = ""
} else {
radioError.innerHTML = "Veuillez choisir une option";
// return false;
}
//Validation Checkbox
if (checkbox.checked === false) {
checkboxError.innerHTML = "Veuillez lire et valider les conditions."
// return false;
}
if ((!valid||!testDate||!testEmail||!checkbox.checked)||(lastName.value === "")||(firstName.value === "")||(nbrTournaments.value === "")) {
return false;
}
launchThanksModal();
}
My HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Reservation</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="modal.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link
href="https://fonts.googleapis.com/css?family=DM+Sans"
rel="stylesheet"
/>
</head>
<body>
<div class="topnav" id="myTopnav">
<div class="header-logo">
<img alt="logo" src="Logo.png" width="auto" height="auto" />
</div>
<div class="main-navbar">
<span>Accueil</span>
<span>Détails de l'évènement</span>
<span>À propos</span>
<span>Contact</span>
<span>Évènements passés</span>
<a href="javascript:void(0);" class="icon" onclick="editNav()">
<i class="fa fa-bars"></i>
</a>
</div>
</div>
</div>
<main>
<div class="hero-section">
<div class="hero-content">
<h1 class="hero-headline">
Marathon national<br>
de jeux vidéos
</h1>
<p class="hero-text">
Vous aimez jouer ? Notre prochain évènement gaming est ouvert
aux réservations... Places limitées !
</p>
<button class="btn-signup modal-btn">
je m'inscris
</button>
</div>
<div class="hero-img">
<img src="./bg_img.jpg" alt="img" />
</div>
<button class="btn-signup modal-btn">
je m'inscris
</button>
</div>
<!--MODAL-->
<div class="bground">
<div class="content">
<span class="close"></span>
<div class="modal-body">
<form
id="reserve"
name="reserve"
action="index.html"
method="get"
onsubmit="return validate();"
>
<div
class="formData">
<label for="firstName">Prénom</label><br>
<input
class="text-control"
type="text"
id="firstName"
name="firstName"
minlength="2"
/><br>
<span class="firstname-error errormsg"></span>
</div>
<div
class="formData">
<label for="lastName">Nom</label><br>
<input
class="text-control"
type="text"
id="lastName"
name="lastName"
/><br>
<span class="lastname-error errormsg"></span>
</div>
<div
class="formData">
<label for="email">Email</label><br>
<input
class="text-control"
type="email"
id="email"
name="email"
/><br>
<span class="mail-error errormsg"></span>
</div>
<div
class="formData">
<label for="birthdate">Date de naissance</label><br>
<input
class="text-control"
type="date"
id="birthdate"
name="birthdate"
/><br>
<span class="birthdate-error errormsg"></span>
</div>
<div
class="formData">
<label for="quantity">À combien de tournois GameOn avez-vous déjà participé ?</label><br>
<input type="number" class="text-control" id="quantity" name="quantity" min="0" max="99"><br>
<span class="tournament-error errormsg"></span>
</div>
<p class="text-label">A quel tournoi souhaitez-vous participer cette année ?</p>
<div
class="formData">
<input
class="checkbox-input"
type="radio"
id="location1"
name="location"
value="New York"
/>
<label class="checkbox-label" for="location1">
<span class="checkbox-icon"></span>
New York</label
>
<input
class="checkbox-input"
type="radio"
id="location2"
name="location"
value="San Francisco"
/>
<label class="checkbox-label" for="location2">
<span class="checkbox-icon"></span>
San Francisco</label
>
<input
class="checkbox-input"
type="radio"
id="location3"
name="location"
value="Seattle"
/>
<label class="checkbox-label" for="location3">
<span class="checkbox-icon"></span>
Seattle</label
>
<input
class="checkbox-input"
type="radio"
id="location4"
name="location"
value="Chicago"
/>
<label class="checkbox-label" for="location4">
<span class="checkbox-icon"></span>
Chicago</label
>
<input
class="checkbox-input"
type="radio"
id="location5"
name="location"
value="Boston"
/>
<label class="checkbox-label" for="location5">
<span class="checkbox-icon"></span>
Boston</label
>
<input
class="checkbox-input"
type="radio"
id="location6"
name="location"
value="Portland"
/>
<label class="checkbox-label" for="location6">
<span class="checkbox-icon"></span>
Portland</label
>
</div>
<span class="radio-button-error errormsg"></span>
<div
class="formData">
<input
class="checkbox-input"
type="checkbox"
id="checkbox1"
checked
/>
<label class="checkbox2-label" for="checkbox1" required>
<span class="checkbox-icon"></span>
J'ai lu et accepté les conditions d'utilisation.
</label><p class="checkbox-error errormsg"></p>
<input class="checkbox-input" type="checkbox" id="checkbox2" />
<label class="checkbox2-label" for="checkbox2">
<span class="checkbox-icon"></span>
Je Je souhaite être prévenu des prochains évènements.
</label>
<br>
</div>
<input
class="btn-submit"
type="submit"
class="button"
value="C'est parti"
/>
</form>
</div>
</div>
</div>
<!-- FIN MODAL-->
<!-- MODAL CONFIRMATION ENVOI-->
<div class="thanks-modal-container">
<div class="overlay modal-triggers"></div>
<div class="thanks-modal-content">
<p class="thanks-modal-text">Merci, votre réservation a bien été prise en compte</p>
<button class="thanks-modal-close-btn">OK</button>
</div>
</div>
<!-- FIN MODAL CONFIRMATION ENVOI-->
</main>
<footer>
<p class="copyrights">
Copyright 2014 - 2022, GameOn Inc.
</p>
</footer>
<script src="modal.js"></script>
</body>
</html>
Thanks a lot !
You need event.preventDefault() on form submission so it does not reload the page, and handle your submission logic with only js. Use something like this:
<form onsubmit="submitForm(event)">
<input type="text">
<button type="submit">Submit</button>
</form>
<script>
function submitForm(event){
event.preventDefault();
// your custom submission logic
// display modal on success
}
</script>
I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
function appearafter2() {
document.getElementById("buttonappear2").style.display = "block";
document.getElementById("button2").style.display = "block";
document.getElementById("hinzufuegen2").style.display = "none";
}
function myFunction2() {
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList3").appendChild(cln);
}
function deleteFunction2() {
var list3 = document.getElementById("myList3");
var divs = Array.from(list3.getElementsByTagName("div"));
// If the number of divs is 4, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 4) {
document.getElementById("button2").style.display = "none";
}
var lastDivToDelete2 = divs[divs.length - 1];
list3.removeChild(lastDivToDelete2);
}
function allFunction2() {
myFunction2();
appearafter2();
}
#button2 {
display: none;
}
#buttonappear2 {
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#myList3 {
display: none;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="allFunction2()">
+ Loc de munca
</div>
<div id="myList3">
<div id="button2" onclick="deleteFunction2()">Șterge</div>
<div id="myList4">
<div id="addingNewJob">
<label class="label-job-input" for="job-input-1">Numele firmei</label>
<select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
<option value="scoala">școală profesională</option>
<option value="lic">liceu</option>
<option value="fac">facultate</option></select>
<label class="label-job-input" for="job-input-2">Postul ocupat
</label>
<input size="1" type="text" id="job-input-3" /><br />
<label class="label-data2" for="job-input-3">din data</label><label class="label-data2" for="job-input-4">până la data</label><br />
<input type="number" style="width: 48%" />
<input type="number" style="width: 50%; margin-left: 6px" />
</div>
</div>
</div>
<div onclick="allFunction2()" id="buttonappear2">
+ Loc de munca
</div>
Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
Updated the answer, check if this is what you are trying to achieve.
function myFunction2() {
var cln = '<div class="list-item">'+
'<div id="addingNewJob">'+
'<label class="label-job-input" for="job-input-1">Numele firmei</label>'+
'<select size="1" type="text" id="job-input-1" /></div>';
document.getElementById("myList3").innerHTML+=cln;
document.getElementById("buttonappear2").classList.remove('hide');
document.getElementById("button2").classList.remove('hide');
document.getElementById("hinzufuegen2").classList.add('hide');
}
function deleteFunction2() {
var divs = Array.from(document.querySelectorAll(".list-item"));
if(divs.length>0){
var lastDivToDelete2 = divs[divs.length - 1];
document.getElementById("myList3").removeChild(lastDivToDelete2);
}
if(divs.length==1){
document.getElementById("buttonappear2").classList.add('hide');
document.getElementById("button2").classList.add('hide');
document.getElementById("hinzufuegen2").classList.remove('hide');
}
}
.hide{
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="myFunction2()">+ Loc de munca</div>
<div id="myList3">
<div id="button2" class="hide" onclick="deleteFunction2()">Șterge</div>
</div>
școala generală școală profesională liceu facultate
<label class="label-job-input" for="job-input-2">Postul ocupat</label>
<form>
<input size="1" type="text" id="job-input-3" />
<br />
<label class="label-data2" for="job-input-3">din data</label>
<label class="label-data2" for="job-input-4">până la data</label>
<br />
<input type="number" style="width: 48%;" />
<input type="number" style="width: 50%; margin-left: 6px;" />
</form>
<div onclick="myFunction2()" class="hide" id="buttonappear2">+ Loc de munca</div>
Context: I'm trying to create a button so that every time someone presses it, it adds 3 new divs (one for the Ativo (ativo = stock in English), one for Quota%, and another for Perda Potencial). I'm starting by simply adding the Ativo div first to try this out. Then, I created a valuePercentage variable that would take the amount of slices on the pie chart (amount of slices = amount of ativos divs) so that I can get the Quota% (the quota is essentially 100 divided by the number of Ativos. Initially, I have 5 fixed so each Ativo will be 20%. This % should be adjusted as the user presses the "Add stock" button. If the user adds 5 more ativos, this Quota% should be 10, etc).
Problem: The method to add divs that I'm using isn't working and I was looking at using node.cloneNode, but I'd like to generate new ativo IDs and not clone them. Could we mix node.cloneNode with template literals and a for loop so that the 3 divs are cloned, but the index of each ativo is changed (from 1 to 15 for example?). I currently have ativo1, ativo2, ativo3, ativo4 and ativo 5, and when the user presses the button, it should add new divs with ids like ativo 6, ativo7, etc
//https://www.youtube.com/watch?v=y17RuWkWdn8&ab_channel=WebDevSimplified
// usar este video para criar uma função que faça append de um novo div com atributos semelhantes aos outros para permitir ao usuario adicionar novos ativos com o cloque de um butao
let valuePercentage;
////////////////////////////////////////////////////////////////////////////////////
//Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)
let perda;
////////////////////////////////////////////////////////////////////////////////////
//Load google chart graphs
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
//This value percentage is essentially the "Quota". This value will be 100% divided by the amount of slices (essentialy, divided by ativo1, ativo2, ativo3... ativo(i))
// Function that will add new "Ativo", a new "Quota%" and a new "Perda potencial%".
function addStock() {
for (let i = 6; i <= 15; i++) {
let input = document.getElementById(`ativo${i}`).value;
input = input.length + 1;
document.getElementbyId(`field_div`).innerHTML = document.getElementbyId(`field_div`).innerHTML + `
<div class="td" id="field_div"><input type="text" size="5" value="${input}" class="stock" id="ativo${i}"
onchange="drawChart();" /> </div>`
}
}
//Function that removes the divs added
// function removeStock(id) {
// for (let i = 6; i <= 10; i++) {
// document.getElementById(`ativo${i}`).innerHTML = "";
// }
// }
//1º Get the lenght, 2º get the IDs
// let ativoArray;
// for (let i = 1; i <= 15; i++) { // cap the max amount of ativos at 15
// ativoArray = document.getElementById(`ativo${i}`)
// //console.log(ativoArray)
// }
////////////////////////////////////////////////////////////////////////////////////
//Function that will be passed by the "Draw Graph" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
function drawChart() {
const slices = [];
for (let i = 1; i <= 5; i++) {
slices.push({
ativo: document.getElementById(`ativo${i}`).value,
quota: parseFloat(document.getElementById(`quota${i}`).value)
})
}
valuePercentage = (100 / slices.length);
//Calculate the Loss (Perda)
let sum = 0.0;
for (let i = 0; i < slices.length; i++) {
sum += slices[i].quota;
};
perda = 100.0 - sum;
//Create data table with input data
var data = new google.visualization.DataTable();
data.addColumn("string", "Ativo");
data.addColumn("number", "Quota");
data.addRows([
...slices.map(slice => ([slice.ativo, slice.quota])),
["Perda", perda],
]);
//Styling
let options = {
'legend': 'right',
pieHole: 0.3,
pieSliceText: 'value',
is3D: true,
colors: ['#FBB117', '#6AA121', '#728FCE', '#4863A0', '#7D0552', '#FF0000'],
backgroundColor: '#DFCFBE',
chartArea: {
left: 50,
right: 50,
top: 70
}
};
var chart = new google.visualization.PieChart(
document.getElementById("piechart")
);
chart.draw(data, options);
}
document.querySelector(".row").addEventListener("input", function (e) {
const tgt = e.target;
if (tgt.classList.contains("perda")) {
perda = Number(tgt.closest(".tr").querySelector(".quota").value =
valuePercentage - tgt.value * 0.2) //O 20 será alterado para a expressao de numero de quotas a dividir por 100%
//console.log(perda)
// quota * perda potencial; var = quota * +- perda potencial / 100
//quota - var;
//let var = perda/risco potencial
//console.log(20 - perda);
//isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
}
});
////////////////////////////////////////////////////////////////////////////////////
{
box-sizing: content-box;
}
/* Set additional styling options for the columns */
.column {
float: left;
}
/* Set width length for the left, right and middle columns */
.left {
width: 30%;
}
.right {
width: 80%;
}
.row:after {
content: "";
display: table;
clear: both;
height: 100%;
}
.td {
display: inline-block;
width: 120px;
text-align: center;
font-family: 'Trebuchet MS', sans-serif;
}
.tr {
font-family: 'Trebuchet MS', sans-serif;
}
.button1 {
width: 20%;
margin-left: 35%;
margin-right: 25%;
margin-top: 10px;
font-family: 'Trebuchet MS', sans-serif;
}
.button2 {
width: 20%;
margin-left: 35%;
margin-right: 25%;
margin-top: 10px;
font-family: 'Trebuchet MS', sans-serif;
}
.piechart {
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body style="background-color:#DFCFBE">
<div class="row">
<div class="column left">
<form id=" form">
<div class="tr">
<div class="td">Ativo </div>
<div class="td">Quota % </div>
<div class="td">Perda Potencial % </div>
</div>
<div class="tr" id="wrapper">
<div class="td" id="field_div"><input type="text" size="5" value="TSLA" class="stock" id="ativo1"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota1"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda1" />
</div>
</div>
<div class="tr" id="wrapper">
<div class="td" id="field_div"><input type="text" size="5" value="AAPL" class="stock" id="ativo2"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota2"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda2" />
</div>
</div>
<div class="tr" id="wrapper">
<div class="td" id="field_div"><input type="text" size="5" value="MSFT" class="stock" id="ativo3"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota3"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda3" />
</div>
</div>
<div class="tr" id="wrapper">
<div class="td" id="field_div"><input type="text" size="5" value="EURUSD" class="stock"
id="ativo4" />
</div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota4" />
</div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda4" />
</div>
</div>
<div class="tr" id="wrapper">
<div class="td" id="field_div"><input type="text" size="5" value="BITCOIN" class="stock" id="ativo5"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" id="quota5"
onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" id="perda5" />
</div>
</div>
<button class="button2" type="button" onclick="addStock();">Add Stock</button>
<button class="button1" type="button" onclick="drawChart();">Draw Graph</button>
</form>
</div>
<div class="column right" style="position:relative;width:70%">
<div class=" piechart" id="piechart" style="position:absolute;right:0px;top:0px;width: 900; height: 590px;">
</div>
</div>
</body>
So, first of all like i did mentioned in the comments, you use multiple identifiers attributes, this is not html5 valid. Identifier attributes need to be unique, about performance etc.., not reason why you post.
I did change you html and used data attributes, we create a Wrapper that we define with data-type="wrapper". We stored the index inside of the html by using another data attribute data-index="1". beware data attributes are slower then storing your data in javascript, but for this small script you will not have any gain by doing so.
We use some dom traversal to get the right elements we want. Also i did change your html with the button onclick="addStock(event);" this was because i like to use the event.currentTarget and event.target properties to have more control about my code instead of using this.
In the example below you can have an idea how to future improve your code. deleting like you said you were trying is now kinda easy.
If you have more questions, feel free to comment.
Code;
function addStock(event) {
// find the last Wrapper [data-set="wrapper"]
let lastWrapper = event.currentTarget.form.querySelector(`[data-type="wrapper"]:last-of-type`);
// get the index of the last Wrapper
let lastIndex = lastWrapper.dataset.index;
//not more then 15
if ( lastIndex < 15 ) {
//clone the wrapper
let clonerNode = lastWrapper.cloneNode(true);
//change index of cloner Wrapper
clonerNode.dataset.index = parseInt(lastIndex, 10) + 1;
//changes values;
clonerNode.querySelector(`.stock`).value = "NEW STOCK";
clonerNode.querySelector(`.quota`).value = 0;
//append clonernode after lastWrapper
lastWrapper.insertAdjacentElement('afterend', clonerNode);
}
//https://www.youtube.com/watch?v=y17RuWkWdn8&ab_channel=WebDevSimplified
// usar este video para criar uma função que faça append de um novo div com atributos semelhantes aos outros para permitir ao usuario adicionar novos ativos com o cloque de um butao
let valuePercentage;
////////////////////////////////////////////////////////////////////////////////////
//Get all the values for each stock input and the quota variation (as "Perda potencial" increases, Quota decreases by a ratio of 1:5 and vice-versa)
let perda;
////////////////////////////////////////////////////////////////////////////////////
//Load google chart graphs
google.charts.load("current", {
packages: ["corechart"]
});
google.charts.setOnLoadCallback(drawChart);
//This value percentage is essentially the "Quota". This value will be 100% divided by the amount of slices (essentialy, divided by ativo1, ativo2, ativo3... ativo(i))
// Function that will add new "Ativo", a new "Quota%" and a new "Perda potencial%".
function addStock(event) {
// find the last Wrapper [data-set="wrapper"]
let lastWrapper = event.currentTarget.form.querySelector(`[data-type="wrapper"]:last-of-type`);
// get the index of the last Wrapper
let lastIndex = lastWrapper.dataset.index;
//not more then 15
if ( lastIndex < 15 ) {
//clone the wrapper
let clonerNode = lastWrapper.cloneNode(true);
//change index of cloner Wrapper
clonerNode.dataset.index = parseInt(lastIndex, 10) + 1;
//changes values;
clonerNode.querySelector(`.stock`).value = "NEW STOCK";
clonerNode.querySelector(`.quota`).value = 0;
//append clonernode after lastWrapper
lastWrapper.insertAdjacentElement('afterend', clonerNode);
}
console.log(lastIndex);
}
//Function that removes the divs added
// function removeStock(id) {
// for (let i = 6; i <= 10; i++) {
// document.getElementById(`ativo${i}`).innerHTML = "";
// }
// }
//1º Get the lenght, 2º get the IDs
// let ativoArray;
// for (let i = 1; i <= 15; i++) { // cap the max amount of ativos at 15
// ativoArray = document.getElementById(`ativo${i}`)
// //console.log(ativoArray)
// }
////////////////////////////////////////////////////////////////////////////////////
//Function that will be passed by the "Draw Graph" button so that everytime the user clicks the button, it takes the new input values and updates the pie chart
function drawChart() {
const slices = [];
for (let i = 1; i <= 5; i++) {
// slices.push({
// ativo: document.getElementById(`ativo${i}`).value,
// quota: parseFloat(document.getElementById(`quota${i}`).value)
// })
slices.push({
ativo: document.querySelector(`div [data-type="wrapper"][data-index="${i}"] .stock`).value,
quota: parseFloat(document.querySelector(`div [data-type="wrapper"][data-index="${i}"] .quota`).value)
})
}
valuePercentage = (100 / slices.length);
//Calculate the Loss (Perda)
let sum = 0.0;
for (let i = 0; i < slices.length; i++) {
sum += slices[i].quota;
};
perda = 100.0 - sum;
//Create data table with input data
var data = new google.visualization.DataTable();
data.addColumn("string", "Ativo");
data.addColumn("number", "Quota");
data.addRows([
...slices.map(slice => ([slice.ativo, slice.quota])), ["Perda", perda],
]);
//Styling
let options = {
'legend': 'right',
pieHole: 0.3,
pieSliceText: 'value',
is3D: true,
colors: ['#FBB117', '#6AA121', '#728FCE', '#4863A0', '#7D0552', '#FF0000'],
backgroundColor: '#DFCFBE',
chartArea: {
left: 50,
right: 50,
top: 70
}
};
var chart = new google.visualization.PieChart(
document.getElementById("piechart")
);
chart.draw(data, options);
}
document.querySelector(".row").addEventListener("input", function(e) {
const tgt = e.target;
if (tgt.classList.contains("perda")) {
perda = Number(tgt.closest(".tr").querySelector(".quota").value =
valuePercentage - tgt.value * 0.2) //O 20 será alterado para a expressao de numero de quotas a dividir por 100%
//console.log(perda)
// quota * perda potencial; var = quota * +- perda potencial / 100
//quota - var;
//let var = perda/risco potencial
//console.log(20 - perda);
//isto teria que atualizar sempre que a perda potencial % aumenta ou diminui. Neste momento, apenas faz a soma, nao retira o valor quando perda potencial % diminui e a quota aumenta
}
});
////////////////////////////////////////////////////////////////////////////////////
{
box-sizing: content-box;
}
/* Set additional styling options for the columns */
.column {
float: left;
}
/* Set width length for the left, right and middle columns */
.left {
width: 30%;
}
.right {
width: 80%;
}
.row:after {
content: "";
display: table;
clear: both;
height: 100%;
}
.td {
display: inline-block;
width: 120px;
text-align: center;
font-family: 'Trebuchet MS', sans-serif;
}
.tr {
font-family: 'Trebuchet MS', sans-serif;
}
.button1 {
width: 20%;
margin-left: 35%;
margin-right: 25%;
margin-top: 10px;
font-family: 'Trebuchet MS', sans-serif;
}
.button2 {
width: 20%;
margin-left: 35%;
margin-right: 25%;
margin-top: 10px;
font-family: 'Trebuchet MS', sans-serif;
}
.piechart {
width: 100%;
height: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<body style="background-color:#DFCFBE">
<div class="row">
<div class="column left">
<form id=" form">
<div class="tr">
<div class="td">Ativo </div>
<div class="td">Quota % </div>
<div class="td">Perda Potencial % </div>
</div>
<div class="tr" data-type="wrapper" data-index="1">
<div class="td" data-type="field_div"><input type="text" size="5" value="TSLA" class="stock" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
</div>
</div>
<div class="tr" data-type="wrapper" data-index="2">
<div class="td" data-type="field_div"><input type="text" size="5" value="AAPL" class="stock" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
</div>
</div>
<div class="tr" data-type="wrapper" data-index="3">
<div class="td" data-type="field_div"><input type="text" size="5" value="MSFT" class="stock" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
</div>
</div>
<div class="tr" data-type="wrapper" data-index="4">
<div class="td" data-type="field_div"><input type="text" size="5" value="EURUSD" class="stock" />
</div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" />
</div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
</div>
</div>
<div class="tr" data-type="wrapper" data-index="5">
<div class="td" data-type="field_div"><input type="text" size="5" value="BITCOIN" class="stock" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="20" value="20" class="quota" onchange="drawChart();" /> </div>
<div class="td"><input type="number" min="0" max="100" value="0" class="perda" />
</div>
</div>
<button class="button2" type="button" onclick="addStock(event);">Add Stock</button>
<button class="button1" type="button" onclick="drawChart();">Draw Graph</button>
</form>
</div>
<div class="column right" style="position:relative;width:70%">
<div class=" piechart" id="piechart" style="position:absolute;right:0px;top:0px;width: 900; height: 590px;">
</div>
</div>
</body>
I have a table that has some values that whenever the edit button on that row gets clicked all of the values on that row get passed to the corresponding input tags so they can be edited.
This is my code:
$(document).ready(function() {
//"use strict";
cargarDatos();
$('#frmContacto').submit(function(event) {
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
guardarDatos();
cargarDatos();
});
$('input').on('blur', function() {
$(this).addClass('marcado');
//alert(this.value);
});
$('.btnEditar').on('click', function(event) {
event.preventDefault();
//Here is where I call a function that is supposed to pass values to the inputs on my html page so I could update the values
});
$('#inputFoto').on('change', function(e) {
precargarImagen(this);
});
$(window).load(function() {
$(document).ready($('#efecto1').addClass('animacion1'));
// $(document).ready($('#efecto2').addClass('animacion1'));
// cargarDatos();
});
});
/*jshint latedef:false */
function guardarDatos() {
name = $('#inputNombre').val();
direccion = $('#inputDireccion').val();
telefono = $('#inputTelefono').val();
fecha = $('#inputFecha').val();
email = $('#inputEmail').val();
color = $('#inputColor').val();
dataFoto = $("#imgFoto").attr("src");
/*alert("Sus datos son: \n" + nombre + "\n"
+ direccion + "\n" + telefono + "\n"
+ fecha + "\n" + email+ "\n" + color);*/
contacto = {
nombre: name,
direccion: direccion,
telefono: telefono,
fecha: fecha,
email: email,
color: color,
foto: dataFoto
};
contactos.push(contacto);
console.log(JSON.stringify(contactos));
localStorage.setItem('lstcontactos2', JSON.stringify(contactos));
}
/*jshint latedef:false */
function cargarDatos() {
var data = localStorage.getItem('lstcontactos2');
contactos = data && JSON.parse(data);
if (contactos == null)
contactos = new Array();
$('#tablaContactos').bootstrapTable({
data: contactos
});
}
function btnEditar(value) {
console.log("valueformat " + value);
return '<span class="glyphicon glyphicon-pencil"></span>';
}
function imgFoto(value) {
return '<img id="imgFoto" src="' + value +
'" style="width:auto;height:160px;">';
}
function precargarImagen(inputfile) {
var file = inputfile.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
$(".file-caption-name").html(file.name);
$(".file-preview-frame").empty();
$(".file-preview-frame").
append('<img id="imgFoto" src="' + reader.result +
'" style="width:auto;height:160px;">');
};
reader.readAsDataURL(file);
inputfile.val(img.src);
} else {
alert("Archivo no soportando!");
}
}
.marcado {
color: #ff0000;
border: 1px solid #0000ff;
}
.desmarcado {
color: #00000;
border: 0;
}
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
text-align: right;
opacity: 0;
filter: alpha(opacity=0);
opacity: 0;
background: none repeat scroll 0 0 transparent;
cursor: inherit;
display: block;
}
.file-preview-frame {
display: table;
margin: 8px;
height: 160px;
width: 160px;
border: 1px solid #ddd;
box-shadow: 1px 1px 5px 0px #a2958a;
padding: 6px;
float: left;
text-align: center;
vertical-align: middle;
transition: all .4s ease-in-out;
}
.file-preview-frame:hover {
box-shadow: 3px 3px 5px 0px #333;
cursor: pointer;
background-size: 150% 150%;
transform: scale(2.2);
}
/* Shrink */
.hvr-shrink {
display: inline-block;
vertical-align: middle;
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
-webkit-transition-duration: 0.3s;
transition-duration: 0.3s;
-webkit-transition-property: transform;
transition-property: transform;
}
.hvr-shrink:hover,
.hvr-shrink:focus,
.hvr-shrink:active {
-webkit-transform: scale(0.9);
transform: scale(0.9);
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset=utf-8>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>Contactos</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.css">
<link rel="stylesheet" href="estilos.css" />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="script.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/bootstrap-table.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.7.0/locale/bootstrap-table-es-AR.min.js"></script>
</head>
<body>
<div class="container">
<h1>Contactos personales</h1>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Listado</a>
</div>
</div>
</nav>
<div class="row show-grid">
<div class="animacion1">
<div class="col-sm-6">
<table id="tablaContactos" class="table table-hover" data-toggle="table" data-search="true" data-row-style="rowStyle" data-show-refresh="true" data-show-toggle="true" data-show-columns="true">
<thead>
<tr>
<th data-field="nombre" data-sortable="true">Nombre</th>
<th data-field="direccion" data-sortable="true">Dirección</th>
<th data-field="email" data-sortable="true">Email</th>
<th data-field="fecha" data-sortable="true">Fecha</th>
<th data-field="telefono" data-sortable="true" data-visible="false">Telefono</th>
<th data-field="color" data-sortable="false" data-visible="false">Color</th>
<th data-field="foto" data-sortable="false" data-formatter="imgFoto">Foto</th>
<th data-field="email" data-formatter="btnEditar"></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">Agregar/editar contacto</div>
<div class="panel-body">
<form class="form-horizontal" id="frmContacto">
<div class="form-group">
<label for="inputFoto" class="col-sm-2 control-label">Foto</label>
<div class="col-sm-10">
<div class="file-preview-frame">
<img src="" style="width:auto;height:160px;">
</div>
<input type="file" class="form-control file" id="inputFoto" data-show-upload="false" required="true">
</div>
</div>
<div class="form-group">
<label for="inputNombre" class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputNombre" placeholder="Ingrese nombre" required>
</div>
</div>
<div class="form-group">
<label for="inputDireccion" class="col-sm-2 control-label">Dirección</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputDireccion" required placeholder="Ingrese dirección personal">
</div>
</div>
<div class="form-group">
<label for="inputTelefono" class="col-sm-2 control-label">Telefono</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="inputTelefono" placeholder="Ingrese # telefónico" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Ingrese Email" required>
</div>
</div>
<div class="form-group">
<label for="inputFecha" class="col-sm-2 control-label">Fecha de nacimiento</label>
<div class="col-sm-10">
<input type="date" class="form-control" id="inputFecha" placeholder="Ingrese su fecha de nacimiento" required>
</div>
</div>
<div class="form-group">
<label for="inputColor" class="col-sm-2 control-label">Color favorito</label>
<div class="col-sm-10">
<input type="color" class="form-control" id="inputColor">
</div>
</div>
<div class="form-group">
<label for="inputURL" class="col-sm-2 control-label">Página Web</label>
<div class="col-sm-10">
<input type="url" class="form-control" id="inputURL" placeholder="Ingrese su página web">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btnGuardar">Guardar OK</button>
<button type="button" class="btn btn-default">Cancelar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
How can I do this with jquery or is there a better way of doing this? and also whenever I click the btnGuardar submit button how can I update table without having to refresh the page to see the new added values?
This is my second answer on this question. It have the same structure as the earlier answer but this one picks up all fields on the same row (wich have the same class) at once.
function edit(key) {
var x = document.getElementsByClassName("prow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
var x = document.getElementsByClassName("inputrow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "initial";
}
document.getElementById('inputA' + key ).value = document.getElementById('pA' + key ).innerHTML;
document.getElementById('inputB' + key ).value = document.getElementById('pB' + key ).innerHTML;
document.getElementById('inputC' + key ).value = document.getElementById('pC' + key ).innerHTML;
}
function save(key) {
var x = document.getElementsByClassName("prow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "initial";
}
var x = document.getElementsByClassName("inputrow" + key);
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById('pA' + key ).innerHTML = document.getElementById('inputA' + key ).value;
document.getElementById('pB' + key ).innerHTML = document.getElementById('inputB' + key ).value;
document.getElementById('pC' + key ).innerHTML = document.getElementById('inputC' + key ).value;
}
*{
font-family: Arial, Helvetica, sans-serif;
}
p {
margin:0px;
}
input[type=text] {
display:none;
height:12px;
width:45px;
}
table, th, td {
border: 2px solid darkslategray ;
background:darkseagreen ;
border-collapse: collapse;
margin:0px;
padding:0px;
}
<table>
<form id=formA>
<tr>
<td>
<p id=pA1 class=prow1>value 1</p><input id=inputA1 type="text" name="A" class=inputrow1 value="value 1"></td>
<td><p id=pB1 class=prow1>value 2</p><input id=inputB1 type="text" name="B" class=inputrow1 value="value 2">
</td>
<td><p id=pC1 class=prow1>value 3</p><input id=inputC1 type="text" name="C" class=inputrow1 value="value 3">
</td>
<td><button type="button" onclick="edit(1)">edit</button><button type="button" onclick="save(1)">save</button>
</td>
</tr>
<tr>
<td>
<p id=pA2 class=prow2>value 1</p><input id=inputA2 type="text" name="D" class=inputrow2 value="value 1"></td>
<td><p id=pB2 class=prow2>value 2</p><input id=inputB2 type="text" name="E" class=inputrow2 value="value 2">
</td>
<td><p id=pC2 class=prow2>value 3</p><input id=inputC2 type="text" name="F" class=inputrow2 value="value 3">
</td>
<td><button type="button" onclick="edit(2)">edit</button><button type="button" onclick="save(2)">save</button>
</td>
</tr>
<tr>
<td colspan=4>
<input type="submit" value="Submit" style="width:100%;">
</td>
</tr>
</form>
</table>
This would be comment but I can't add a comment yet.
It may be a good idea to look at an MVVM library such as:
http://knockoutjs.com/
https://angularjs.org/
http://vuejs.org/
If you're new to the idea of MVVM I would recommend looking at knockout, although it is probably the more complex option the tutorials are excellent: http://learn.knockoutjs.com/
This line gets the text from an element and stores it in the variable y:
var y = document.getElementById('text id').innerHTML;
This line places the value stored in the y variable on the edit box:
document.getElementById('input text id').value = y;
Here it comes a working example:
function edit(key) {
document.getElementById('p' + key).style.display = "none";
document.getElementById('input' + key).style.display = "initial";
var yy = document.getElementById('p' + key).innerHTML;
document.getElementById('input' + key).value = yy;
}
function save(key) {
document.getElementById('p' + key).style.display = "initial";
document.getElementById('input' + key).style.display = "none";
var xx = document.getElementById('input' + key).value;
document.getElementById('p' + key).innerHTML = xx;
}
*{
font-family: Arial, Helvetica, sans-serif;
}
p {
margin:0px;
}
input[type=text] {
display:none;
height:12px;
width:40px;
}
table, th, td {
border: 2px solid tomato;
background:gold;
border-collapse: collapse;
margin:0px;
padding:0px;
}
<table>
<form id=formA>
<tr>
<td>
<p id=pA>value 1</p><input id=inputA type="text" name="A" value="value 1"></td><td><p id=pB>value 2</p><input id=inputB type="text" name="B" value="value 2">
</td>
</tr>
<tr>
<td>
<button type="button" onclick="edit('A')">edit 1</button><button type="button" onclick="save('A')">save 1</button></td>
<td><button type="button" onclick="edit('B')">edit 2</button><button type="button" onclick="save('B')">save 2</button>
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Submit" style="width:100%;">
</td>
</tr>
</form>
</table>
how do I fill the stars of a star rating already everything running the calculation and it took a echo in the variable calculation to see the result he would return me and he is me returning right however I am unable to leave it filled for example to note that 3.3 product and fill it three stars and 30% of the fourth as I do it? where I have to play my variable to show it in the stars?
code:
<form id="rating" action"rating.php" method="post">
<input type="hidden" name="id" id="idd" value="$idprod" />
<div class="vote">
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="1" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="2" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="3" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="4" />
<i class="fa" id="fa"></i>
</label>
<label>
<input id="stars" class="radioo" type="radio" name="fb" value="5" />
<i class="fa" id="fa"></i>
</label>
</div>
</form>
jquery:
$('.vote label i.fa').on('click mouseover',function(){
// remove classe ativa de todas as estrelas
$('.vote label i.fa').removeClass('active');
// pegar o valor do input da estrela clicada
var val = $(this).prev('input').val();
//percorrer todas as estrelas
$('.vote label i.fa').each(function(){
/* checar de o valor clicado é menor ou igual do input atual
* se sim, adicionar classe active
*/
var $input = $(this).prev('input');
if($input.val() <= val){
$(this).addClass('active');
}
});
$("#voto").html(val); // somente para teste
});
//Ao sair da div vote
$('.vote').mouseleave(function(){
//pegar o valor clicado
var val = $(this).find('input:checked').val();
//se nenhum foi clicado remover classe de todos
if(val == undefined ){
$('.vote label i.fa').removeClass('active');
} else {
//percorrer todas as estrelas
$('.vote label i.fa').each(function(){
/* Testar o input atual do laço com o valor clicado
* se maior, remover classe, senão adicionar classe
*/
var $input = $(this).prev('input');
if($input.val() > val){
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
}
$("#voto").html(val); // somente para teste
});
php:
$id = $_GET['cod'];
$sql = mysql_query("SELECT * FROM produtos WHERE id_produto = $id");
$test = mysql_query("SELECT votos, pontos FROM produtos WHERE id_produto = $id");
$aux = mysql_fetch_array($sql);
$idprod = $aux['id_produto'];
$row = mysql_fetch_array($test);
$voto = $row['votos'];
$ponto = $row['pontos'];
$calc = round(($ponto/$voto),1);
If I understand your question correctly, you are not sure how to fill stars dynamically from a PHP value for a calculated rating.
I put together this solution, the fiddle is here. The best way to do this (outside of AJAX) is to pass the calculated rating into a data attribute on the rating element. Then have your JS fill stars based on that as is shown in the jQuery. I also shown how you can use a click event to fill a hidden input field and re-evalulate the star filling to represent what was clicked.
If later a form is not submitted, you can post the new rating via ajax (best solution really to avoid a page change just to add a new rating). Or if a form is submitted, just make sure the divs are inside the element.
Here the code:
PHP:
//Do your calcuations
$calc = round(($ponto/$voto),1);
HTML
<div class="rating" data-calc="<?php echo $calc; ?>">
<div class="star" data-seq="1">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="2" >
<div class="cnt">
<img class="full2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="3">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="4">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<div class="star" data-seq="5">
<div class="cnt">
<img class="full" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Stj%C3%A4rna.svg/2000px-Stj%C3%A4rna.svg.png" />
</div>
<img class="empty" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/1088px-Five-pointed_star.svg.png" />
</div>
<input type="hidden" name="rating" value="" />
</div>
jQuery
function fillStarOnPercent(star, percent)
{ var fill = 25 * percent;
star.children('.cnt').css({'width' : fill +'px'});
}
function fillStars(parent, fullStars, percent){
for(var i = 1; i < 6; i++)
{
var star = parent.find('.star[data-seq="'+i+'"]');
if(i < fullStars)
fillStarOnPercent(star, 1);
if(i == fullStars)
fillStarOnPercent(star, percent);
if(i > fullStars)
fillStarOnPercent(star, 0);
}
}
$(document).ready(function() {
jQuery('.rating').each(function() {
var calc = jQuery(this).data('calc');
var fullStars = Math.floor(calc);
if(fullStars == calc)
var percent = 1
else
var percent = calc - fullStars;
fillStars( jQuery(this), fullStars, percent );
});
jQuery('.rating').on('click', '.star', function() {
var rating = jQuery(this).data('seq');
fillStars(jQuery(this).parent(), rating, 1 );
jQuery(this).parent().children('input[name="rating"]').val(rating);
});
});
CSS
.star {width:25px;height:25px; position:relative; float:left;}
.star img {display:block; position:absolute; top:0; left:0; width:25px; height:25px;}
.cnt {position:absolute; top:0; left:0; overflow:hidden; width:25px; height:25px}