How to write a calculation in JS? - javascript

If the amount is correct, then that amount appears in a dialog box if it is less than 150 €, or a 10% discount if more than 150 €, or a 20% if it is higher than 250 €.
<form name="monForm" action="#" method="post">
Montant de la facture : <input type="text" name="montant" id="montant" /></br>
<input type="button" onclick="paiement(document.monForm.montant.value)" name="valider" id="valider" value="Valider" />
</form>
<script>
function paiement(montant)
{
if (montant == "" || isNaN(montant)) //Pour s'assurer que le champ est renseigné et est numérique
{
alert("Montant de la facture en erreur");
return false;
}
montant = parseInt (montant);
if (isNaN(montant) == false && montant < 150 )
{
var mtn = document.getElementById("montant");
alert('Le montant de la facture est : "'+mtn.value+"'");
}
if (isNaN(montant) == false && montant > 150)
{
// calcul de la remise
alert('Vous bénéficiez d une remise de : "'+remise.value+"'");
}
var j = 20;
if (isNaN(montant) == false && montant > 250)
{
}
}
</script>
All what I want is to give :
If amount is less than 250 euros the discount will be 20%
And is is less than 150 euros the discount will be 10%

// Lorsque le DOM sera prêt:
// - L'event 'load' (paramètre 1) sera lancé
// - La fonction (paramètre 2) sera alors exécutée
window.addEventListener('load', function() {
// Lorsque l'utilisateur cliquera sur le bouton valider:
// - L'event 'click' (paramètre 1) sera lancé
// - La fonction (paramètre 2) sera alors exécutée
document.getElementById('valider').addEventListener('click', function() {
// Ciblage de l'input contenant le montant dans le DOM
var inputElement = document.getElementById('montant');
// Récupération de la valeur contenue dans l'input
var stringValue = inputElement.value;
// Transtypage de cette valeur textuelle en valeur numérique
var floatValue = parseFloat(stringValue);
// Si le transtypage a échoué ou le montant est négatif
if (isNaN(floatValue) || floatValue < 0) {
alert('Montant de la facture incorrect');
return;
}
// Déclaration de la remise
var remise;
// Si le montant de la facture est dans l'interval [0;150[
if (floatValue < 150) {
remise = 0; // pourcent
}
// Si le montant de la facture est dans l'interval [150;250[
else if (floatValue < 250) {
remise = 10; // pourcent
}
// Si le montant de la facture est dans l'interval [250;+inf[
else {
remise = 20; // pourcent
}
// Calcul du montant final à 2 chiffres significatifs
var finalValue = (floatValue - (floatValue * (remise / 100))).toFixed(2);
// Affichage du résultat final
alert('Vous bénéficiez d\'une remise de '+remise+'%\nSoit une facture totale de '+finalValue);
});
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Montant de la facture :
<input type="text" id="montant"/><br/>
<input type="button" id="valider" value="Valider"/>
</body>
</html>

Related

Check input form need two click to be validated

I need to click two times on my button to validate my form,
I have a event listener like this :
btnCartSend.addEventListener('click', function(){
checkInput();
window.location="confirm.html "
})
Then it call
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
I put the whole project on my github and here you have the cart file with both functions and others: https://github.com/lliolla/P5-onorico/blob/master/frontend/js/cart.js
I have cloned your project and find some omissions that you are using shoppingCart.length everywhere while shoppingCart is having null initially, so wherever you are using the length or any other property, please first check if that variable is null or not.
After fixing all this, I have run the code and it is validating the form with a single click.
Check your code or replace the cart.js with the below code I have corrected at some places.
//déclaration des variables
let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart')); // recuperer le panier convertit en javascript
console.log('shoppingCart',shoppingCart)
let orderInfos = JSON.parse(localStorage.getItem('orderInfos')); // recuperer le retour API convertit en javascript
console.log('orderInfos',orderInfos)
let form =document.getElementById("form") // formulaire
let btnCartSend =document.getElementById("btnCartSend") // bouton envoi
let tableCartRows = document.getElementById("tableCartRows")// corps du tableau
let tableFoot = document.getElementById("tableFoot")//pied du tableau
let table=document.getElementById("table") // tableau entier
let tableTitle=document.getElementById("tableTitle") // h2
let orderModal = document.getElementById('orderModal')// modal de confirmation de commande
//variables info clients a vérifier
let fristName = document.getElementById("inputFristName").value;
let lastName= document.getElementById("inputLastName").value;
let address = document.getElementById("inputAddress").value;
let zip = document.getElementById("inputZip").value;
let city = document.getElementById("inputCity").value;
let email = document.getElementById("InputMail").value;
function showCart(){
//au chargement de la page génerer dynamiquement le panier si shoppingcart est plein sinon on affiche panier vide avec bouton de retour a teddiesHome.html
if (shoppingCart && shoppingCart.length <= 0) {
// on masque le cart le formulaire et son bouton et on affiche un retour à la page des produits
tableTitle.style.display = "none";
tableCart.style.display = "none";
form.style.display = "none";
btnCartSend.style.display = "none";
let h2 = document.createElement("h2");
table.appendChild(h2);
h2.textContent ="Votre panier est vide ";
let p = document.createElement("p");
table.appendChild(p);
p.textContent ="Faites un petit tour dans nos boutiques et laissez-vous tenter";
var a = document.createElement("a");
p.appendChild(a);
a.setAttribute('class','btn btn-secondary btn-lg btn-block');
a.setAttribute('href','teddiesHome.html');
a.setAttribute('role','button');
a.textContent = "Continuer mes achats";
}else{
totalCartPrice ();// total price du panier
//verifier si il y a des doublons
if(shoppingCart) {
createTableCart(); //sinon afficher le panie
}
}
}
showCart()
function delateItemCart(index){
//supprimer un teddy en fonction de son index dans teddyArray
console.log ("suprimer le teddy dans shopping cart",index, shoppingCart[index])
shoppingCart.splice(index,1)
console.log ("suprimer le teddy dans shopping cart", shoppingCart)
//vide le localstorage
localStorage.clear();
//mettre à jour le local storage avec nouveau panier
localStorage.setItem('shoppingCart',JSON.stringify(shoppingCart) ) ;
totalCartPrice ();
// recharger la page
document.location.reload();
//}
}
// on fait une boucle pour acceder à tous les boutons supprimer
let bntDelated = document.querySelectorAll('.bntDelated') //boutons supprimer
for (i=0 ;i<bntDelated.length ; i++ ){
console.log("bntDelated", bntDelated[i])
bntDelated[i].addEventListener("click", function(){ // au clic sur sup on suprimer le teddy coorepondant dans le shopping cart
let index = Array.from(bntDelated).indexOf(event.target) ;
console.log("click pour suprimer envoi l'index, ",index)
delateItemCart(index);
})
}
// au clic sur le btn envoyer la commande
btnCartSend.addEventListener('click', function(){
checkInput();// on verifie le format des input
sendToApi(); // on envoi les donnees a l'api et on recuperer le num de commande
//si tout est ok on affiche le modal avec un num de commande et le prix total
window.location="confirm.html "
})
function totalCartPrice (){
if(shoppingCart) {
let totalCart = 0;
for ( let i=0; i<shoppingCart.length ; i++ ){
let cartQte = shoppingCart[i].qte;
let cartprice = shoppingCart[i].price;
totalCart += cartQte * cartprice
localStorage.setItem('totalCart',JSON.stringify(totalCart) );
}
}
}
function createTableCart(){// on affiche dynamiquement le panier sous forme de tableau
// on boucle le shopping cart pour afficher une ligne par teddy
for ( let i=0; i<shoppingCart.length ; i++ ){
let tr1 = document.createElement("tr");
tableCartRows.appendChild(tr1);
let th7 = document.createElement("th");
tr1.appendChild(th7);
th7.setAttribute('scoop','row');
th7.textContent="counter ligne";
let td = document.createElement("td");
tr1.appendChild(td);
let teddyname =shoppingCart[i].name ;
td.textContent= teddyname;
td.setAttribute("id","Name")
let td1 = document.createElement("td");
tr1.appendChild(td1);
let teddyColor = shoppingCart[i].colors;
td1.textContent=teddyColor;
td.setAttribute("id","Color")
let price = shoppingCart[i].price + "€";
let td2 = document.createElement("td");
tr1.appendChild(td2);
td2.textContent=price;
let td3 = document.createElement("td");
tr1.appendChild(td3);
td3.setAttribute("class","counter");
let div = document.createElement("div");
td3.appendChild(div);
div.setAttribute("class","number");
div.setAttribute("id","number");
div.textContent=shoppingCart[i].qte;
// let div1 = document.createElement("div")
// td3.appendChild(div1)
// div1.setAttribute("class","counter-clic")
// let i1 = document.createElement("i")
// div1.appendChild(i1)
// i1.setAttribute("class","fas fa-plus plus")
// let i2 = document.createElement("i")
// div1.appendChild(i2)
// i2.setAttribute("class","fas fa-minus minus")
// let td4 = document.createElement("td")
// tr1.appendChild(td4)
// td4.textContent= subTotal
let td5 = document.createElement("td");
tr1.appendChild(td5);
td5.setAttribute("class","text-center");
let i3 = document.createElement("i");
td5.appendChild(i3);
i3.setAttribute("class","fas fa-times-circle bntDelated");
}
let tr2 = document.createElement("tr");
tableFoot.appendChild(tr2);
let td6 = document.createElement("td");
tr2.appendChild(td6);
td6.setAttribute("colspan","2");
let td7 = document.createElement("td");
tr2.appendChild(td7);
td7.textContent = "Total"
let totalCart = localStorage.getItem('totalCart')
let td8 = document.createElement("td");
tr2.appendChild(td8);
td8.setAttribute("colspan","3");
td8.setAttribute('class','text-right');
td8.textContent = totalCart + "€";
}
function checkInput(){
if (fristName.length == 0){
alert("test 1");
}else if(lastName.length == 0){
alert("test 2");
}else if(address.length == 0){
alert("test 3");
}else if(zip.length != 5){
alert("test 4");
}else if(city.length == 0){
alert("test 5");
}else if(email.length == 0){
alert("test 6");
}else {
console.log('send to api');
sendToApi();
}
}
function sendToApi(){
// crerer un objet qui va recuperer la value de chaque input du formulaire
//creation de la class client
class customer{
constructor(fristName,lastName,address,city,email){
this.lastName = lastName;
this.fristName = fristName;
this.address = address;
this.city = city;
this.email = email;
}
}
// objet contenant les infos du formulaire
let newCustumer = new customer (lastName,fristName, address,city,email)
// creer un tableau pour envoyer uniquement les ID des teddy
//recupérer le shoppingCart
let apiCart =JSON.parse(localStorage.getItem("shoppingCart")) ;
console.log("apiCart",apiCart)
let apiCartArray = []; // tableau des id des teddy
//parcourir le tableau et recuperer les id des teddy
if(apiCart) {
for (let i=0; i<apiCart.length; i++){
apiCartArray.push(apiCart[i].id)
console.log("send api id",apiCartArray)
}
}
// POST API
fetch("http://localhost:3000/api/teddies/order", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contact: {
firstName: newCustumer.fristName,
lastName: newCustumer.lastName,
address: newCustumer.address,
city: newCustumer.city,
email: newCustumer.email,
},
products: apiCartArray,
}),
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => {
localStorage.setItem("orderInfos", JSON.stringify(data));
})
.catch((error) => console.log("erreur de type : ", error));
}

Return Var Value In User Message

I'm new to programming and I'm currently learning JavaScript. Sorry if my code is not the most readable ever :)
I'm using this function here to calculate mortgage values (messages and business rules are in Portuguese/Brazilian standards):
function calculaFinanc() {
var amount1 = document.getElementById("amount1").value;
var amount2 = document.getElementById("amount2").value;
var teto = (amount1 / 100) * 30;
var parcela = amount2 / 360;
if (Math.round(teto) < Math.round(parcela)) {
return [document.getElementById("userMessage").className += 'alert alert-danger' , document.getElementById("userMessage").innerHTML = "<p>Você não pode financiar este imóvel. O valor da parcela de seu financiamento não poderá ultrapassar 30% valor da sua renda mensal</p>"];
} else { //... rest omitted for brevity
Inside the <p> tag in the return statement, I'd like to display the value of variables "teto" and "parcela". How on earth do I do that? No matter what I tried, it doesn't show anything (or it just displays the text "teto").
e.g. this is how I'd like to return:
return [document.getElementById("userMessage").className += 'alert alert-danger' , document.getElementById("userMessage").innerHTML = "<p>Você não pode financiar este imóvel. O valor da parcela de seu financiamento não poderá ultrapassar 30% valor da sua renda mensal ($var_teto)</p>"];
Just add it into the string.
return [document.getElementById("userMessage").className += 'alert alert-danger' , document.getElementById("userMessage").innerHTML = "<p>Você não pode financiar este imóvel. O valor da parcela de seu financiamento não poderá ultrapassar 30% valor da sua renda mensal "+teto+"</p>"];

Button don't redirect using onClick - Javascript HTML

i'm working in a simple web, and i use a botton for enter to the principal page, but nothing happens, only work if i don't use the function, see:
With this don´t work:
The button:
<center><input type="button" name="Entrar" onClick="iniciar()" value=" Ingresar " >
The function "iniciar()":
<script type="text/javascript" language="javascript">
function iniciar(){
var value
var clase,nombre,validate="ATS1"
nombre=window.prompt("Digite su primer nombre");
clase=prompt("Digite su codigo de seccion de clase (letras en mayuscula)");
if (clase==validate){
value = 3;
}
else{
value = 0;
}
if (value == 3){
window.alert("Ingreso exitoso, presione Aceptar.")
var pag="formulario.html"
alert("Aceptado \nPulse Aceptar y sera redireccionado en 2 segundos.", setTimeout("location.href=pag",2000))
//Dos segundos para redireccionar
}
else{
alert("Lo sentimos mucho, usted no tiene acceso a la pagina. Usted pertenece a otro curso, adios.")
close()}
}
</script>
But if i don't use the button, i use the script of java directly (no function) in the page this is working (redirect)
<script type="text/javascript" language="javascript">
var value
var clase,nombre,validate="ATS1"
nombre=window.prompt("Digite su primer nombre");
clase=prompt("Digite su codigo de seccion de clase (letras en mayuscula)");
if (clase==validate){
value = 3;
}
else{
value = 0;
}
if (value == 3){
window.alert("Ingreso exitoso, presione Aceptar.")
var pag="formulario.html"
alert("Aceptado \nPulse Aceptar y sera redireccionado en 2 segundos.", setTimeout("location.href=pag",2000))
//Dos segundos para redireccionar
}
else{
alert("Lo sentimos mucho, usted no tiene acceso a la pagina. Usted pertenece a otro curso, adios.")
close()}
</script>
I hope that they can understand me :/
Thanks
=================================================================
See all the code (i use the syntax that #Moogs send me it's work :D):
<!doctype html>
<html>
<head>
<title>Formulario</title>
<script type="text/javascript" language="javascript">
function cerrar(){
close()
}
function iniciar(){
var value
var clase,nombre,validate="ATS1"
nombre=window.prompt("Digite su primer nombre");
clase=prompt("Digite su codigo de seccion de clase (letras en mayuscula)");
if (clase==validate){
value = 3;
}
else{
value = 0;
}
if (value == 3){
window.alert("Ingreso exitoso, presione Aceptar.")
var pag="formulario.html"
alert("Aceptado \nPulse Aceptar y sera redireccionado en 2 segundos.");
setTimeout(function() {
window.location.href = pag;
}, 2000)
//Dos segundos para redireccionar
}
else{
alert("Lo sentimos mucho, usted no tiene acceso a la pagina. Usted pertenece a otro curso, adios.")
close()}
}
document.querySelector('[type="button"]').onclick = iniciar;
</script>
</head>
<body>
<center><font face="Lucida handwriting"><h1><b><i>Formulario</i></b></h1></font></center><hr>
<br>
<center><input type="button" name="Entrar" onClick="iniciar()" value=" Ingresar ">
<input type="button" name="Salir" onClick="cerrar()" value=" Salir ">
</center>
</body>
</html>
Use a function for the setTimeout callback instead of an eval string and place the timeout after the alert instead of as an alert argument.
function iniciar() {
var value = 0;
var clase;
var nombre;
var validate = "ATS1";
nombre = prompt("Digite su primer nombre");
clase = prompt("Digite su codigo de seccion de clase (letras en mayuscula)");
if (clase === validate) {
value = 3;
}
if (value == 3) {
alert("Ingreso exitoso, presione Aceptar.");
var pag = "formulario.html"
alert("Aceptado \nPulse Aceptar y sera redireccionado en 2 segundos.");
setTimeout(function() {
alert('redirect');
window.location.href = pag;
}, 2000)
} else {
alert("Lo sentimos mucho, usted no tiene acceso a la pagina. Usted pertenece a otro curso, adios.");
close();
}
}
document.querySelector('[type="button"]').onclick = iniciar;
<input type="button" name="Entrar" value=" Ingresar " >
Here i use your code it's working fine:
Check it:
<html>
<head>
</head>
<body>
<style>
</style>
<script type="text/javascript" language="javascript">
function iniciar(){
alert("hello");
var value
var clase,nombre,validate="ATS1"
nombre=window.prompt("Digite su primer nombre");
clase=prompt("Digite su codigo de seccion de clase (letras en mayuscula)");
if (clase==validate){
value = 3;
}
else{
value = 0;
}
if (value == 3){
window.alert("Ingreso exitoso, presione Aceptar.")
var pag="formulario.html"
alert("Aceptado \nPulse Aceptar y sera redireccionado en 2 segundos.", setTimeout("location.href=pag",2000))
//Dos segundos para redireccionar
}
else{
alert("Lo sentimos mucho, usted no tiene acceso a la pagina. Usted pertenece a otro curso, adios.")
close()}
}
</script>
<center><input type="button" name="Entrar" onClick="iniciar()" value=" Ingresar " >
</body>
</html>
Check Fiddle here.

Node.js, Mongoose function return an error the first time but not the second

I have a function which return some elements from my MongoDB database but I have a problem with my variables. It says that one of my variable isn't defined the first time but then if I refresh, the error disappear. So I think it's an error of global variable defined in an inner scope which can't be accessed the first time or something like that.
So here's my code :
exports.findQuestion = function findQuestion()
{
var tabRand = new Array(); // on déclare un nouveau tableau où on va stocker les jets de rand
var query = boardModel.find(null); // on cherche toutes les entrées dans la collection
query.exec(function (err, tabQuestion) {
if (err) { throw err;}
var rep = tabQuestion[0];
var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau
var i = false;
tabRand[0] = 0;
while (i == false)
{
for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents
{
if(random != rand) // si le rand est différent on le garde
{
i = true;
if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise
{
tabRand = new Array();
}
}
}
tabRand.push[rand]; // on ajoute le rand précédent à tabRand
rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau
}
quest = rep.question[rand-1].quest; // on récupère le resultat attendu
repJuste = rep.question[rand-1].rep_j;
repFausse1 = rep.question[rand-1].rep_f1;
repFausse2 = rep.question[rand-1].rep_f2;
gainQ = rep.question[rand-1].gain;
nomTr = rep.question[rand-1].name_t;
});
return [quest, repJuste, repFausse1, repFausse2, gainQ, nomTr];
}
So the first time, it says that quest is not defined but then everything works well ...
PS : Sorry for the half-French, half-English code ^^
I see one problem here, you can't return something in a asynchronous function, you should use a callback.
If you want to understand it :
You do your asynchronous query (and you do something in your callback with the result tabQuestion)
and your return something but you're not sure your async function is done.
try async.js to help you manage your asynchronous problems
EDIT:
async.parallel([
function(callback){
boardModel.find().exec(function (err, tabQuestion) {
if (err) { throw err;}
var rep = tabQuestion[0];
var rand = Math.floor((Math.random()*rep.question.length+1)); // random sur le tableau
var i = false;
tabRand[0] = 0;
while (i == false)
{
for(var random in tabRand) // on vérifie le résultat du rand avec les rand précédents
{
if(random != rand) // si le rand est différent on le garde
{
i = true;
if(tabRand.length-1 == rep.question.length) // si la taille de tabRand est égale à la longueur du tableau de questions de la collection alors on le reinitialise
{
tabRand = new Array();
}
}
}
tabRand.push[rand]; // on ajoute le rand précédent à tabRand
rand = Math.floor((Math.random()*rep.question.length+1)); // et on en fait un nouveau
}
quest = rep.question[rand-1].quest; // on récupère le resultat attendu
repJuste = rep.question[rand-1].rep_j;
repFausse1 = rep.question[rand-1].rep_f1;
repFausse2 = rep.question[rand-1].rep_f2;
gainQ = rep.question[rand-1].gain;
nomTr = rep.question[rand-1].name_t;
});
callback(null, quest, repJuste, repFausse1, repFausse2, gainQ, nomTr);
}],
function(err){
if(err){
console.log(err);
}else{
console.timeEnd('chargement bd');
socket.emit('event', {'quest': quest, 'repJuste' : repJuste }); //add all your params
}
});

To count number of rows in a table if the rows were created after the DOM loaded

I create rows after the DOM loaded, but I want to know how to count number of rows for eliminate the last.
I have this.
<script type="text/javascript">//Procesamiento del formulario.
$(document).ready(function(){
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function(){ //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr >td').length; //Obtener el número de celdas
var capa = document.getElementById("elementos"); //Obtener el elemento con el id elementos
var tr = ("tr"); //Crear una tag tr
capa.appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="'+nuevaLetra+cuentaTr+'" name="columna'+nuevaLetra+cuentaTr+'" required/></td>').appendTo('#elementos'); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII+1 >= 65 && ASCII+1 <= 90) || (ASCII+1 >= 97 && ASCII+1 <= 122)) ? ASCII+1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2){
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function(){ //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
</script>
What I can to do?
Thank you!
I'm sorry for my English. I can't speak English well.
Looks like there are some problems on how the tr is appended to the table, try
$(document).ready(function () {
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function () { //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr:first >td').length; //Obtener el número de celdas
var capa = $("#elementos"); //Obtener el elemento con el id elementos
var tr = $('#tr').appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="' + nuevaLetra + cuentaTr + '" name="columna' + nuevaLetra + cuentaTr + '" required/></td>').appendTo(tr); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII + 1 >= 65 && ASCII + 1 <= 90) || (ASCII + 1 >= 97 && ASCII + 1 <= 122)) ? ASCII + 1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2) {
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function () { //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
var cuentaTr = $('#elementos >tbody >tr').length - 1; (already in your code) should give you the number of rows (minus one). Maybe make a jsfiddle so we can debug what's going on?

Categories

Resources