how to replace a single choice with a select my cart - javascript

For now I have a cart in javascript that works
But when I click the add to cart button
there is only one product added
I would like to replace this with a select so that the user can choose the number of articles to add
I tried to modify the code but when I select a quantity and I click on add to cart
It's always two that adds up
var MonPanier = (function() {
panier = [];
function Item(nom, prix, quantite) {
this.nom = nom;
this.prix = prix;
this.quantite = quantite;
}
function savepanier() {
console.log("saving",panier)
// sessionStorage.setItem('MonPanier', JSON.stringify(panier));
}
function loadpanier() {
// panier = JSON.parse(sessionStorage.getItem('MonPanier'));
panier = []
}
// if (sessionStorage.getItem("MonPanier") != null) {
// loadpanier();
// }
//variable objet
var obj = {};
obj.ajouter_produit_dans_panier = function(nom, prix, quantite) {
for (var item in panier) {
if (panier[item].nom === nom) {
//panier[item].quantite ++ ; ancien code
panier[item].quantite;
savepanier();
return;
}
}
var item = new Item(nom, prix, quantite);
panier.push(item);
savepanier();
}
obj.setquantiteForItem = function(nom, quantite) {
for (var i in panier) {
if (panier[i].nom === nom) {
panier[i].quantite = quantite;
break;
}
}
};
obj.enlever_produit_de_panier = function(nom) {
for (var item in panier) {
if (panier[item].nom === nom) {
panier[item].quantite--;
if (panier[item].quantite === 0) {
panier.splice(item, 1);
}
break;
}
}
savepanier();
}
obj.enlever_produit_de_panier_tous = function(nom) {
for (var item in panier) {
if (panier[item].nom === nom) {
panier.splice(item, 1);
break;
}
}
savepanier();
}
obj.clearpanier = function() {
panier = [];
savepanier();
}
obj.totalquantite = function() {
var totalquantite = 0;
for (var item in panier) {
totalquantite += panier[item].quantite;
}
return totalquantite;
}
obj.totalpanier = function() {
var totalpanier = 0;
for (var item in panier) {
totalpanier += panier[item].prix * panier[item].quantite;
}
return Number(totalpanier.toFixed(2));
}
obj.listpanier = function() {
var panierCopy = [];
for (i in panier) {
item = panier[i];
itemCopy = {};
for (p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = Number(item.prix * item.quantite).toFixed(2);
panierCopy.push(itemCopy)
}
return panierCopy;
}
return obj;
})();
$('.ajouter-panier').click(function(event) {
event.preventDefault();
var nom_option = "";
var prix_option = 0;
var nom = $(this).data('nom');
var prix = Number($(this).data('prix')) + prix_option;
var quantite = $(this).data('select');
MonPanier.ajouter_produit_dans_panier(nom, prix, quantite);
//MonPanier.ajouter_produit_dans_panier(nom, prix,1); ancien code
afficherpanier();
});
$('.clear-panier').click(function() {
MonPanier.clearpanier();
afficherpanier();
});
$('.choix_livraison').click(function() {
const cases = document.querySelectorAll('input[name="choix_livraison"]');
for (const x of cases) {
if (x.checked) {
afficherpanier();
}}
});
function afficherpanier() {
var panierArray = MonPanier.listpanier();
var output = "";
var countart=0;
var countart2=0;
var count=0;
for(var i in panierArray) {
output += "<div class='row' style='border-style: ridge; border-width: 1px; border-color: #8ebf42; background-color: #d9d9d9;margin-bottom:5px;'>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'><button class='btn btn-danger effacer-item' data-nom='" + panierArray[i].nom + "'>X</button></div>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].nom + "</div>"
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].prix.toFixed(0) + " euro</div>"
+ "<div class='form-inline col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'><div class='input-group'><button class='btn btn-primary moins-item' data-nom='" + panierArray[i].nom + "'>-</button>"
+ "<input type='number' min='1' class='form-control item-quantite' style='width:55px !important' data-nom='" + panierArray[i].nom + "' value='" + panierArray[i].quantite + "'>"
+ "<button class='btn btn-primary plus-item' data-nom='" + panierArray[i].nom + "'>+</button></div></div>"
//+ ' = '
+ "<div class='col' style='text-align: center;border-left: solid;padding-left: 5px;padding-right: 5px;'>" + panierArray[i].total + " euros</div>"
+ "</div>";
count++;
countart += panierArray[i].quantite; // somme des unités d'articles
countart2 = countart
}
$('.show-panier').html(output);
if (Livraison == 3)
{
// % du prix total total correspondant au prix de la livraison
const cases = document.querySelectorAll('input[name="choix_livraison"]');
//const cases = document.querySelectorAll('input[name="ajout");
for (const x of cases) {
if (x.checked) {
let nom_choix_livraison = x.dataset.nom;
let prix_choix_livraison = x.value;
//console.log(panierArray[i] );
let prix_et_livraison = (( (MonPanier.totalpanier()*Poucentage_Livraison))) + Number(prix_choix_livraison) + Number(Forfait_Livraison ) ;
document.getElementById('amount').value = prix_et_livraison ;
$('.total-panier').html(prix_et_livraison.toFixed(2));
document.getElementById('livraison-detail').innerHTML ="<div class='col' style='text-align:right;background-color: #78b8df;visibility:hidden;'> (" + nom_choix_livraison + ")" + prix_choix_livraison + " euro(s)</div>";
document.getElementById('remise').innerHTML =MonPanier.totalpanier()*Poucentage_Livraison_opposse ;
document.getElementById('nouveau_prix').innerHTML =(MonPanier.totalpanier()- (MonPanier.totalpanier()*Poucentage_Livraison_opposse));
document.getElementById('frais-fixe').innerHTML =Forfait_Livraison ;
document.getElementById("prix_depart").innerHTML = MonPanier.totalpanier();
document.getElementById("countart_bas").innerHTML = countart;
document.getElementById("countart_haut").innerHTML = countart;
break;
}
}
}
$('.total-panier-modal').html(MonPanier.totalpanier());
$('.total-quantite').html(MonPanier.totalquantite());
if ((Qte_Minimum == 1) && (Number.isInteger(MonPanier.totalquantite() / Qte_Minimum_Valeur) == false) && (MonPanier.totalquantite() != 0))
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_bad;
}
else if ((Qte_Minimum == 1) && (Number.isInteger(MonPanier.totalquantite() / Qte_Minimum_Valeur) == true) && (MonPanier.totalquantite() != 0))
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_ok;
}
else if (Qte_Minimum == 1)
{
document.getElementById('qte_minimum_report').innerHTML = txt_qte_minimum_defaut;
}
else if (Qte_Minimum == 0)
{
document.getElementById('qte_minimum_report').innerHTML = "";
}
}
$('.show-panier').on("click", ".effacer-item", function(event) {
var nom = $(this).data('nom')
MonPanier.enlever_produit_de_panier_tous(nom);
afficherpanier();
})
$('.show-panier').on("click", ".moins-item", function(event) {
var nom = $(this).data('nom')
MonPanier.enlever_produit_de_panier(nom);
afficherpanier();
})
$('.show-panier').on("click", ".plus-item", function(event) {
var nom = $(this).data('nom')
MonPanier.ajouter_produit_dans_panier(nom);
afficherpanier();
})
$('.show-panier').on("change", ".item-quantite", function(event) {
var nom = $(this).data('nom');
var quantite = Number($(this).val());
MonPanier.setquantiteForItem(nom, quantite);
afficherpanier();
});
afficherpanier();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row mt-3">
<div class="col-md-4">
<p>Produit 02 (15.00 €)</p>
</div>
<div class="col-md-2">
<select class="form-control" id="02">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="col-md-6 text-end">
<a style="cursor:pointer;" data-nom="Produit 02" data-prix="15.00" data-select="02" class="btn btn-primary ajouter-panier">Add to Cart</a>
</div>
</div>

Related

Can't add more than 10 rows to my datatable

I want to add dynamically rows to my DataTable to save them, but when I achieve 10 rows I can't get more than that, and it can't even save it.
// Add row into table
var addRowTable = {
options: {
addButton: "#addToTable",
table: "#addrowExample",
dialog: {}
},
initialize: function() {
this.setVars().build().events()
},
setVars: function() {
return this.$table = $(this.options.table), this.$addButton = $(this.options.addButton), this.dialog = {}, this.dialog.$wrapper = $(this.options.dialog.wrapper), this.dialog.$cancel = $(this.options.dialog.cancelButton), this.dialog.$confirm = $(this.options.dialog.confirmButton), this
},
build: function() {
//var window.table = this.datatable;
return this.datatable = this.$table.DataTable({
aoColumns: [null, null, null, null, null, null, {
bSortable: !1
}],
"sDom": 't'
}), window.dt = this.datatable, this
},
events: function() {
var object = this;
return this.$table.on("click", "button.button-save", function(e) {
e.preventDefault(), object.rowSave($(this).closest("tr"))
}).on("click", "button.button-discard", function(e) {
e.preventDefault(), object.rowCancel($(this).closest("tr"))
}).on("click", "button.button-remove", function(e) {
e.preventDefault();
var $row = $(this).closest("tr");
var sumToRemove = $(this).closest('tr').find('td:eq(5)').text();
//Update sum value
Application.sumCharge -= parseFloat(sumToRemove);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
object.rowRemove($row)
}), this.$addButton.on("click", function(e) {
e.preventDefault(), object.rowAdd()
}), this.dialog.$cancel.on("click", function(e) {
e.preventDefault(), $.magnificPopup.close()
}), this
},
rowAdd: function() {
this.$addButton.attr({
disabled: "disabled"
});
var actions, data, $row;
actions = ['<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-save" data-toggle="tooltip" data-original-title="Save" hidden><i class="icon-drawer" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-discard" data-toggle="tooltip" data-original-title="Discard" hidden><i class="icon-close" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-default button-remove"><i class="icon-trash" aria-hidden="true"></i></button>'].join(" "), data = this.datatable.row.add(["", "", "", "", "", "", actions]), ($row = this.datatable.row(data[0]).nodes().to$()).addClass("adding").find("td:last").addClass("actions"), this.rowEdit($row), this.datatable.order([0, "asc"]).draw()
},
rowCancel: function($row) {
var $actions, data;
$row.hasClass("adding") ? this.rowRemove($row) : (($actions = $row.find("td.actions")).find(".button-discard").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), data = this.datatable.row($row.get(0)).data(), this.datatable.row($row.get(0)).data(data), this.handleTooltip($row), this.datatable.draw())
},
rowEdit: function($row) {
var counter = 0;
var data, object = this;
data = this.datatable.row($row.get(0)).data(), $row.children("td").each(function(i) {
var $this = $(this);
if (counter == 0) {
Application.tableLength++;
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<label style="font-weight: 400 !important">' + Application.tableLength + '</label>');
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" data-provide="datepicker" data-date-autoclose="true" class="form-control input-date" value="' + data[i] + '" required>');
} else if (counter == 2) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 3) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 4) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
}
} else {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="number" step="0.01" class="form-control" value="' + data[i] + '" required>');
}
counter++;
})
},
rowSave: function($row) {
if ($('#form').get(0).reportValidity()) {
var $actions, object = this,
values = [],
counter = 0;
$row.hasClass("adding") && (this.$addButton.removeAttr("disabled"), $row.removeClass("adding")), values = $row.find("td").map(function() {
var $this = $(this),
input = '',
input_value = $this.find("label,input,textarea").val();
if ($this.hasClass("actions")) {
return object.rowSetActionsDefault($row), object.datatable.cell(this).data();
} else {
if (counter == 0) {
input = $this.find("label").text();
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
input = "<input type='hidden' name='date[]' value='" + input_value + "'>";
}
if (counter == 2) {
input = "<input type='hidden' name='description[]' value='" + input_value + "'>";
} else if (counter == 3) {
input = "<input type='hidden' name='details[]' value='" + input_value + "'>";
} else if (counter == 4) {
input = "<input type='hidden' name='charge_observation[]' value='" + input_value + "'>";
}
} else {
input = "<input type='hidden' name='sum[]' value='" + input_value + "'>";
Application.sumCharge += parseFloat(input_value);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
}
counter++;
return $.trim($this.find("label,input,textarea").val()) + input;
}
}), ($actions = $row.find("td.actions")).find(".button-save").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), this.datatable.row($row.get(0)).data(values), this.handleTooltip($row), this.datatable.draw()
}
},
rowRemove: function($row) {
$row.hasClass("adding") && this.$addButton.removeAttr("disabled"), this.datatable.row($row.get(0)).remove().draw()
},
rowSetActionsEditing: function($row) {
$row.find(".on-editing").removeAttr("hidden"), $row.find(".on-default").attr("hidden", !0)
},
rowSetActionsDefault: function($row) {
$row.find(".on-editing").attr("hidden", !0), $row.find(".on-default").removeAttr("hidden")
},
handleTooltip: function($row) {
$row.find('[data-toggle="tooltip"]').tooltip()
}
};
$(function() {
addRowTable.initialize()
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped fixed" cellspacing="0" id="addrowExample">
<thead>
<tr>
<th style="width: 5%">#</th>
<th>{{ __('all.date')}}</th>
<th>{{ __('all.description')}}</th>
<th>{{ __('all.details')}}</th>
<th style="width: 25%">{{ __('all.observation')}}</th>
<th>{{ __('all.sum')}}</th>
<th style="width: 10%">{{ __('all.action')}}</th>
</tr>
</thead>
<tbody>
</tbody>
<tbody>
</tbody>
</table>
<h6 class="p-10 bg-primary text-light text-right">{{ __('all.total sum')}} : <b id="lb-sum">0.00</b> <small>MAD</small></h6>
</div>

while making a shopping cart in javascript i am stuck with a function already in cart?

var products = [
["Product1", 1, "100", "1"],
["Prodict2", 1, "99", "2"],
["Product3", 1, "60", "3"],
["Product4", 1, "50", "4"],
];
function displayProducts() {
//alert('page');
var productdata = "<div class='w3-container ' style='margin:50px 0;'>";
for (i = 0; i < products.length; i++) {
productdata += "<div class='w3-third'><div class='w3-row-padding w3-card w3-container w3-padding-32 w3-center'>" + products[i][0] + "<br> Rs " + products[i][2] + "<br> <button class='w3-btn w3-green w3-round'onclick='addtocart(" + i + ")'>Add to cart</button></div></div>";
}
productdata += "</div>";
document.getElementById('display').innerHTML = productdata;
}
function addtocart(a) {
cart.push(products[a]);
if (products[a] == cart[a]) {
alert("already in cart");
}
displaycart();
}
var cart = [];
function displaycart() {
cartdata = '<table class="w3-table w3-centered w3-border w3-bordered w3-hoverable"><tr><th>Product Name</th><th>Quantity</th><th>Price</th><th>Total</th><th>Delete</th></tr>';
var Subtotal = 0;
for (i = 0; i < cart.length; i++) {
Subtotal += cart[i][1] * cart[i][2]
cartdata += "<tr><td>" + cart[i][0] + "</td><td><button class='w3-green w3-btn w3-circle' onclick= 'lessqty(" + i + ")'> - </button> " + cart[i][1] + " <button class='w3-green w3-btn w3-circle' onclick= 'addqty(" + i + ")'>+</button></td><td>" + cart[i][2] + "</td><td>" + cart[i][1] * cart[i][2] + "</td><td><button class='w3-btn w3-red ' onclick='delElement(" + i + ")'>🗑️ </button></td></tr>"
}
cartdata += '<tr><td></td><td></td><td></td><td><b>' + Subtotal + '</b></td><td></td></tr></table>';
document.getElementById('cart').innerHTML = cartdata;
}
function delElement(a) {
cart.splice(a, 1);
displaycart();
}
function addqty(a) {
cart[a][1] = cart[a][1] + parseInt(1);
displaycart();
}
function lessqty(a) {
cart[a][1] = cart[a][1] - parseInt(1);
if (cart[a][1] == 0) {
alert('quantity cannot be zero!');
cart[a][1] = parseInt(1);
}
displaycart();
}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body onload="displayProducts()">
<div class="" id="display" style="max-width:800px; margin:auto;"></div>
<div class="" id="cart"></div>
</body>
If user tries to add similar product in cart twice it should show an error message to user I tried making id in products array for eg product[0][3] will get id itself to identify if the products is already in cart but not sure how to compare it with the value of array in cart I tried the specific thing in addtocart() function but it was not giving correct output
please suggest me how can i check if the product is already in cart
thanks in advance
You're not checking if the product is already in the cart correctly. Based on your sample data, you should check whether any of the entries in the cart has the same product name as the product being added:
function addtocart(a) {
if (cart.some(p => p[0] == products[a][0])) {
alert("already in cart");
} else {
cart.push(products[a]);
}
displaycart();
}
Note also that you shouldn't add to the cart unless the product is not already in the cart.
Demo:
var products = [
["Product1", 1, "100", "1"],
["Product2", 1, "99", "2"],
["Product3", 1, "60", "3"],
];
function displayProducts() {
//alert('page');
var productdata = "<div class='w3-container ' style='margin:50px 0;'>";
for (i = 0; i < products.length; i++) {
productdata += "<div class='w3-third'><div class='w3-row-padding w3-card w3-container w3-padding-32 w3-center'>" + products[i][0] + "<br> Rs " + products[i][2] + "<br> <button class='w3-btn w3-green w3-round'onclick='addtocart(" + i + ")'>Add to cart</button></div></div>";
}
productdata += "</div>";
document.getElementById('display').innerHTML = productdata;
}
function addtocart(a) {
if (cart.some(p => p[0] == products[a][0])) {
alert("already in cart");
} else {
cart.push(products[a]);
}
displaycart();
}
var cart = [];
function displaycart() {
cartdata = '<table class="w3-table w3-centered w3-border w3-bordered w3-hoverable"><tr><th>Product Name</th><th>Quantity</th><th>Price</th><th>Total</th><th>Delete</th></tr>';
var Subtotal = 0;
for (i = 0; i < cart.length; i++) {
Subtotal += cart[i][1] * cart[i][2]
cartdata += "<tr><td>" + cart[i][0] + "</td><td><button class='w3-green w3-btn w3-circle' onclick= 'lessqty(" + i + ")'> - </button> " + cart[i][1] + " <button class='w3-green w3-btn w3-circle' onclick= 'addqty(" + i + ")'>+</button></td><td>" + cart[i][2] + "</td><td>" + cart[i][1] * cart[i][2] + "</td><td><button class='w3-btn w3-red ' onclick='delElement(" + i + ")'>🗑️ </button></td></tr>"
}
cartdata += '<tr><td></td><td></td><td></td><td><b>' + Subtotal + '</b></td><td></td></tr></table>';
document.getElementById('cart').innerHTML = cartdata;
}
function delElement(a) {
cart.splice(a, 1);
displaycart();
}
function addqty(a) {
cart[a][1] = cart[a][1] + parseInt(1);
displaycart();
}
function lessqty(a) {
cart[a][1] = cart[a][1] - parseInt(1);
if (cart[a][1] == 0) {
alert('quantity cannot be zero!');
cart[a][1] = parseInt(1);
}
displaycart();
}
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body onload="displayProducts()">
<div class="" id="display" style="max-width:800px; margin:auto;"></div>
<div class="" id="cart"></div>
</body>

Block cut from contextmenu using JavaScript

I need block the option "cut" (only this option) from contextmenu.
I only found how to block all the contextmenu using oncontextmenu="return false" but not a single option.
HTML:
<input id="origenInput" name="origen" list="origen" placeholder="Seleccione origen"
oncontextmenu="return false">
<datalist id="origen">
</datalist>
<input id="destinoInput" name="destino" list="destino" placeholder="Seleccione destino"
disabled>
<datalist id="destino">
</datalist>
<br><br>
<span id="textoPrecio"></span>
<br><br>
JavaScript:
ejecutarMultiplesEventos(document.getElementById("destinoInput"), 'change keyup', mostrarInfoPasaje);
(function cargarListadoOrigen() { let origenOption = "";
let origen = ["Amarillo", "Río Alfa"];
for (let i = 0; i < origen.length; ++i) {
origenOption += '<option value="' + origen[i] + '" />';
}
let origenLista = document.getElementById("origen");
origenLista.innerHTML = origenOption;})();
function cargarListadoDestino() {
document.getElementById("textoPrecio").innerHTML = "";
document.getElementById("destinoInput").value = "";
document.getElementById("destinoInput").disabled = true;
let destinoOption = "";
let destino = null;
let destinoLista = null;
let origenSeleccionado = obtenerOrigenIngresado();
if (origenSeleccionado.length >= 3) {
switch (origenSeleccionado) {
case "Amarillo":
destino = ["Barrio Nuevo"];
for (let i = 0; i < destino.length; ++i) {
destinoOption += '<option value="' + destino[i] + '" />';
}
destinoLista = document.getElementById("destino");
destinoLista.innerHTML = destinoOption;
document.getElementById("destinoInput").disabled = false;
break;
case "Río Alfa":
destino = ["El Valle", "Tucute"];
for (let i = 0; i < destino.length; ++i) {
destinoOption += '<option value="' + destino[i] + '" />';
}
destinoLista = document.getElementById("destino");
destinoLista.innerHTML = destinoOption;
document.getElementById("destinoInput").disabled = false;
break;
default:
document.getElementById("textoPrecio").innerHTML = "El origen ingresado es inválido."
document.getElementById("destinoInput").value = "";
document.getElementById("destinoInput").disabled = true;
break;
}
}}
function mostrarInfoPasaje() {
document.getElementById("textoPrecio").innerHTML = "";
let origenSeleccionado = document.getElementById("origenInput").value;
let destinoSeleccionado = document.getElementById("destinoInput").value;
let texto = "El viaje de " + origenSeleccionado + " a " + destinoSeleccionado + " tiene un costo de $";
let valor = obtenerPrecio();
if (destinoSeleccionado.length >= 3) {
switch (origenSeleccionado) {
case "Amarillo":
if (destinoSeleccionado === "Barrio Nuevo") {
document.getElementById("textoPrecio").innerHTML += texto + valor + ".";
} else if (destinoSeleccionado === "") {
document.getElementById("textoPrecio").innerHTML = "";
} else {
document.getElementById("textoPrecio").innerHTML = "El destino ingresado es inválido."
}
break;
case "Río Alfa":
if (destinoSeleccionado === "El Valle") {
document.getElementById("textoPrecio").innerHTML += texto + valor + ".";
} else if (destinoSeleccionado === "Tucute") {
document.getElementById("textoPrecio").innerHTML += texto + valor + ".";
} else if (destinoSeleccionado === "") {
document.getElementById("textoPrecio").innerHTML = "";
} else {
document.getElementById("textoPrecio").innerHTML = "El destino ingresado es inválido."
}
break;
default:
try {
console.error("mostrarInfoPasaje > default");
} catch (e) {
console.log("Catch: ");
console.log(e);
}
break;
}
}
}
The original problem I want to solve is the following (perhaps there is another easier solution): I have two datalists, the second datalist shows the options depending on what is selected in the first, and according to the combination entered I show a text in a <span>, in case the user selects the text entered in the second datalist and press CTRL + X, the <span> is updated correctly, but if the user selects the text entered in the second datalist, right click and select CUT, the <span> is not updated.

Weird JS Behavior With Bootstrap Sliders

So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->
Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>

Dynamic select doesn't work correctly

I got a problem with dynamic selects that not update their content when I change the selection.
I have 2 select inputs:
the first one is to select the category, for example cars, motorbike, etc
and the second should show the various models - for example city car, sport car, etc... if you select cars in the first
But, in my code the second select doesn't update the content when I change the first one and I have to reload the page to see the changes.
I think the problem is in onchange, but I'm not sure, someone know how to resolve?
/*metodo con cui creo la prima select "categoria"*/
this.creaSelectCategoria =
function () {
var categorie = {};
for (var i = 0; i<this.lista.length; i++) {
categorie[this.lista[i].categoria] = true;
}
var s = "";
s+='<option value="null" >Seleziona una Categoria </option>';
for (var i in categorie) {
s += '<option value="' + categorie[i] + '">' + categorie[i] + '</option>';
}
return s;
}
/*metodo con cui creo la seconda select "gruppo"*/
this.creaSelectGruppo =
function () {
var c= document.getElementById("selectCategoria").value;
var gruppi = {};
for (var i = 0; i<this.lista.length; i++) {
if(this.lista[i].categoria==c){
gruppi[this.lista[i].gruppo] = this.lista[i].gruppo;
}
}
var s = "";
s+='<option value="null" >Seleziona un gruppo</option>';
for (var i in gruppi) {
s += '<option value="' + gruppi[i] + '">' + gruppi[i] + '</option>';
}
return s;
}
function inizializza(){
var nodo = caricaXML("elenco.xml");
contenitore.inizializza(nodo);
var nodoSelectCategoria = document.getElementById("selectCategoria");
nodoSelectCategoria.onchange= contenitore.creaSelectCategoria();
var nodoSelectGruppo = document.getElementById("selectGruppo");
nodoSelectGruppo.innerHTML = contenitore.creaSelectGruppo();
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
c1.onclick = cercaNome;
c2.onclick = cercaGruppo;
}
function crea_gruppo(categoria) {
var gruppi = {};
for (var i = 0; i < lista.length; i++) {
if(lista[i].categoria==categoria)
{
gruppi[lista[i].gruppo] = true;
}
}
var s = '<option value="null" >Seleziona gruppo</option>';
for (var i in gruppi) {
s += '<option value="' + i + '">' + i + '</option>';
}
document.getElementById("selectGruppo").innerHTML= s;
}
<select id="selectCategoria" onchange='crea_gruppo(document.getElementById("selectCategoria").options[document.getElementById("selectCategoria").selectedIndex].value);'>
<option selected="selected" value="null">Seleziona tipo di ricerca</option>
<option value="Personaggio">Personaggi</option>
<option value="Arma">Armi</option>
<option value="Veicolo">Veicoli</option>
</select>
<select id="selectGruppo">
<option selected="selected" value="">-seleziona-</option>
</select>
update- now select works, but i ad duplicate entries in the second one
function creaSelectGruppo(categoria){
var v1=[];var v2=[];
for(var i=0;i<contenitore.lista.length;i++){
if(contenitore.lista[i].categoria==categoria){v1.push(contenitore.lista[i]);v2.push(contenitore.lista[i].categoria);}
}
v2.sort();
for(var i=0;i<v2.length;i++){
if(v2[i]==v2[i+1]) not in v2;
}
//fino a qui toglie tutti i duplicati ma lascia un buco nell'array
var s = '<option value="null" >Seleziona gruppo</option>';
for(var i=0;i<v2.length;i++){
try{
if(v2[i]!=undefined){
s += '<option value="' + v1[i].gruppo + '">' + v1[i].gruppo + '</option>';
}
}
catch(Errore){}
}
document.getElementById("selectGruppo").innerHTML=s;
}
Try adding new Option instead of text
function crea_gruppo(categoria) {
var gruppi = {};
for (var i = 0; i < lista.length; i++) {
if(lista[i].categoria==categoria)
{
gruppi[lista[i].gruppo] = true;
}
}
// clear existing entries
while (document.getElementById('selectGruppo').options.length > 0) {
document.getElementById('selectGruppo').removeChild(document.getElementById('selectGruppo').options[0]);
}
document.getElementById("selectGruppo").add(new Option('Seleziona gruppo', ''));
for (var i in gruppi) {
document.getElementById("selectGruppo").add(new Option(i, gruppi[i]));
}
}

Categories