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.
Related
I have a loop running for each selected checkbox in Javascript / Jquery.
Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.
$('#exec-perm').on('click', function () {
var checkboxPermanent;
$('#checks-perm input').each(async function () {
checkboxPermanent = $(this).attr('value');
isChecked = $(this).prop('checked');
permanent = permanent_layers[checkboxPermanent] // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
pixel_permanent = pixel_permanent_layers[checkboxPermanent]
if (permanent) {
if (!isChecked) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
} else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
//map.addLayer(permanent)
//map.addLayer(pixel_permanent)
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
} else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
} else if (isChecked) {
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
//console.log(checkboxPermanent)
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
if (checkboxPermanent == 'altimetria') {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
} else {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
}
});
})
If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..
async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
//var colorRampSLD = getStyles(faz_value, checkboxPermanent)
if (checkboxPermanent == 'altimetria') {
var raster_name = checkboxPermanent + '_' + faz_value
getColors = await getStyles(faz_value, checkboxPermanent)
var colorEnv = '';
for (var j = 0; j < getColors.length; j++) {
if (j + 1 >= getColors.length) {
colorEnv += 'c' + j + ':' + getColors[j]
} else {
colorEnv += 'c' + j + ':' + getColors[j] + ';'
}
}
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + raster_name,
transparent: true,
format: 'image/png',
}).setParams({
env: colorEnv
})
} else {
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
transparent: true,
format: 'image/png',
})
}
}
What Am I missing here?
Check here:
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.
You need to wait for the result of wmsPermRasterCall using await:
console.log(checkboxPermanent)
permanent = await wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
Your code will halt until wmsPermRasterCall is finished.
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>
I have a project in asp.net core. I have a view where I can do a paste operation from an excel table in an input and the javascript code reads the information and creates input controls with that info. How can I handle all of the controls and send them to the controller via submit? I want to save all of the info.
Javascript Code:
<script>
$(document).ready(function () {
$("#excel").bind('paste',
function (e) {
$("#excel").hide();
$("#div_cargar").hide();
var cells = '';
var i_group = '<div class="form-group row">';
var f_group = '</div>';
//Variables del input del id frente
var i_div_1 = '<div class="col-sm-1">';
var f_div = '</div>';
var label_id = '<label class="control-label col-sm-1" for="id_frente">Frente:</label>';
//variables del input de frente
var i_div_7 = '<div class="col-sm-2">';
var f_div_7 = '</div>';
var label_frente = '<label class="control-label col-sm-1" for="frente">Frente:</label>';
var copy = e.originalEvent.clipboardData.getData('Text');
var rows = copy.split('\n');
var id_frente_in = '';
var frente_in = '';
var id_frente = "";
var frente = "";
//Variables partidas
var label_partida = '<label class="control-label col-sm-1" for="frente">Partida:</label>';
var id_partida_in = '';
var partida_in = '';
var partida = '';
var id_partida = '';
//Variables conceptos
var i_div_2 = '<div class="col-sm-2 ">';
var f_div_2 = '</div>';
var i_div_3 = '<div class="col-sm-3">';
var f_div_3 = '</div>';
var i_div_4 = '<div class="col-sm-4">';
var f_div_4 = '</div>';
var label_concepto = '<label class="control-label col-sm-1" for="frente">Concepto:</label>';
var id_concepto_in = '';
var concepto_in = '';
var concepto = '';
var id_concepto = '';
var contadorparaapartado = 0;
//Variables parametros
var i_div_5 = '<div class="col-sm-8">';
var f_div_5 = '</div>';
var label_parametro = '<label class="control-label col-sm-1" for="frente">Parametro:</label>';
var id_concepto_in = '';
var parametro_in = '';
var parametro = '';
var id_partida = '';
var previousrow = "";
var hr = "";
$.each(rows,
function (index, value) {
//Se valida que no este vacio el value
if (value) {
var columna = rows[index].split("\t");
console.log(columna);
columna[0] = columna[0].replace(/["]/g, "'");
columna[1] = columna[1].replace(/["]/g, "'");
//Se valida si cambia de columna
if (columna[0].split(".").length - 1 == 3) {//FRENTES--------------------------------------------------------
id_frente_in = columna[0];
frente_in = columna[1];
//Se arregla el input del id del frente
id_input =
'<input type="text" class="form-control" id="id_frente" name="id_frente_ek[]" req="" value="' +
id_frente_in +
'">';
id_frente = label_id + i_div_1 + id_input + f_div;
id_frenteactual = id_frente;
//Se arregla el input del frente
frente_input =
'<input type="text" class="form-control input-sm" id="frente" name="frente[]" req="" value="' +
frente_in +
'">';
frente = i_div_7 + frente_input + f_div_7;
frenteactual = id_frenteactual + frente;
//$('.frentes').append(id + frente);
} else if (columna[0].split(".").length - 1 == 4) {//PARTIDAS-----------------------------------------------
id_partida_in = columna[0];
partida_in = columna[1];
//Se arregla el input del id de la partida
id_input =
'<input type="text" class="form-control" id="id_partida" name="id_partida_ek[]" req="" value="' +
id_partida_in +
'">';
id_partida = label_partida + i_div_2 + id_input + f_div;
id_partidactual = id_partida;
//Se arregla el input del frente
partida_input =
'<input type="text" class="form-control input-sm" id="partida" name="partida[]" req="" value="' +
partida_in +
'">';
partida = i_div_3 + partida_input + f_div_4;
partidaactual = id_partidactual + partida;
//$(".partidas").append(id + partida);s
}
else if (columna[0] != "") {//CONCEPTOS-----------------------------------------------
var siguienterow = rows[index + 1].split("\t");
if (siguienterow[0] == "") {
if (previousrow != "") {
concepto_in = columna[0] + " (Apartado: " + previousrow + ") ";
} else {
concepto_in = columna[0];
}
//Se arregla el input del id de la concepto
id_input =
'<input type="text" class="form-control" id="id_concepto" name="id_concepto_ek[]" req="" value="' +
concepto_in +
'">';
concepto = label_concepto + i_div_2 + id_input + f_div_4;
conceptoactual = concepto;
} else {
previousrow = columna[0];
}
}
else if (columna[0] == "" && columna[1] != "") {//PARAMETROS-----------------------------------------------
var siguienterow = rows[index + 1].split("\t");
if (siguienterow[0].split(".").length - 1 == 3) {
hr = '<hr>';
}
parametro_in = columna[1];
//Se arregla el input del id de la parametro
id_input =
'<input type="text" class="form-control" id="id_parametro" name="id_parametro_ek[]" req="" value="' +
parametro_in +
'">';
parametro = conceptoactual + label_parametro + i_div_5 + id_input + f_div_5;
//$(".parametros").append(id);
}
if (id_frente == "") {
$(".frentes").append(i_group +
id_frente +
frente +
id_partida +
partida +
parametro +
f_group);
} else {
$(".frentes").append(hr + i_group + id_frente + frente + id_partida + partida + parametro + f_group);
}
id_frente = "";
frente = "";
id_partida = "";
partida = "";
concepto = "";
parametro = "";
}
});
});
});
View code:
<div class="card-header h4">
Index
<a asp-action="Guardar" class="btn btn-success btn-sm float-right" type="submit" title="Guardar
datos"><i class="fas fa-save"></i></a>
<a asp-action="Index" class="btn btn-light btn-sm float-right" title="Crear nueva persona"><i
class="fas fa-redo"></i></a>
</div>
<div class="card-body">
<label class="text-gray-800" id="div_cargar">Cargar datos aquí:</label>
<input class="form-control" id="excel" />
<div class="form-group">
<form asp-action="Guardar">
<div class="frentes">
</div>
</form>
</div>
</div>
Everything generated from the javascript goes into div class "frentes".
You can use the IFormCollection class to handle the form submission.
Something like:
[HttpPost] // assuming you will be posting
public ActionResult YourActionMethod(IFormCollection data)
{
// if you want to iterate
foreach (var keyValuePair in data)
{
...
}
// or if you want to get by form control name
var name = data["name"];
...
}
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]));
}
}
I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}