I have the following structure:
var elementos = ["teste1","teste2","teste3","teste4","teste5","teste6","teste7","teste8","teste9","teste10","teste11","teste12"];
var elementosPossui = [];
function carregaTabelas() {
carregaTabelaElementos();
carregaTabelaElementosPossui();
document.getElementById("conteudoArrays").innerHTML = '['+ elementos.toString()+']['+elementosPossui.toString()+']';
};
function carregaTabelaElementos() {
var k = 0; var tabela = '<table>';
for (var i = 0; i < 4; i++) {
tabela += '<tr>';
for (var j = 0; j < 3; j++) {
if(typeof elementos[k] === "undefined"){
tabela += '<td><span>[0]</span></td>';
k++;
}else{
tabela += '<td><span id="'+elementos[k]+'" onclick="adicionar('+elementos[k]+')">['+elementos[k]+']</span></td>';
k++;
}
}
tabela += '</tr>';
}
tabela += '</table>';
document.getElementById("elementos").innerHTML=tabela;
};
function carregaTabelaElementosPossui() {
var k = 0; var tabela = '<table>';
for (var i = 0; i < 4; i++) {
tabela += '<tr>';
for (var j = 0; j < 3; j++) {
if(typeof elementosPossui[k] === "undefined"){
tabela += '<td><span>[0]</span></td>';
k++;
}else{
tabela += '<td><span id="'+elementosPossui[k]+'" onclick="remover('+elementosPossui[k]+')">['+elementosPossui[k]+']</span></td>';
k++;
}
}
tabela += '</tr>';
}
tabela += '</table>';
document.getElementById("elementosPossui").innerHTML=tabela;
};
adicionar = function(id) {
log = document.getElementById("log");
var index = elementos.lastIndexOf(id);
elementosPossui.push(elementos.splice(index, 1));
carregaTabelas();
log.innerHTML = index;
};
remover = function(id) {
log = document.getElementById("log");
var index = elementosPossui.lastIndexOf(id);
elementos.push(elementosPossui.splice(index, 1));
carregaTabelas();
log.innerHTML = index;
};
carregaTabelas();
Selecione um elemento: <div id="elementos"></div>
<br/><br/>
Elementos adicionados: <div id="elementosPossui"></div>
<br/><br/>
<div id="conteudoArrays"></div>
<br/><br/>
Log: <div id="log"></div>
I'm having trouble adding and removing the element that the user clicked on the array.
The idea is that when you select the element of the first table, it is added in the second, and when you select an element of the second, it is added in the first one, always adding the element to the end of the table.
I thought the combination of methods indexOf
, splice
and push
this way:
index = indexOf(valorDoElemento);
array.push(array.splice(index, 1));
They would solve the problem, instead it simply does not find the element in the array.