Clone function with Switch Case

1

I want to be able to clone the table with the functions cargar_precio and operacion . When writing a name in the input ITEM show me in the input VALOR_RE_MO the price of said ITEM , The script clones correctly, and serve the functions but only for the first row or table, I was reviewing Some responses from the community but do not resemble this situation, I also tried to go through the nodes until the next input but it did not work.

SCRIPT to clone table

$(function(){
// Clona la fila oculta que tiene los campos base, y la agrega al final de 
la tabla
  $("#adicional").on('click', function(){
  $("#tabla tbody tr:eq(0)").clone().removeClass('fila-
    fija').appendTo("#tabla");
});

// Evento que selecciona la fila y la elimina 
$(document).on("click",".eliminar",function(){
    var parent = $(this).parents().get(0);
    $(parent).remove();
    });
});

SCRIPT to show prices

function cargar_precio(valor) {
    var codigo = '';

    switch(valor){
      case '':
          codigo = '';
      break;
      case 'ANCOL':
          codigo = '100';
      break;
      case 'ARTEL':
          codigo = '200';
      break;
  }

  $('#VALOR_RE_MO').val(codigo);

}

function operacion() {

    cargar_precio($('#ITEM').val().toUpperCase());
    var valor = parseInt( $('#VALOR_RE_MO').val()),
    cantidad = parseInt( $('#CANTIDAD').val() );
    if(!isNaN( valor ) && !isNaN( cantidad )){
        $('#VALOR_RE_MO').val( valor * cantidad );
    }
}

HTML

<table id="tabla">

    <label>Item</label>
    <td><input type="text" name="ITEM" id='ITEM' 
    onkeyup='cargar_precio(this.toUpperCase());' autofocus="autofocus">
    </td>

    <label>Cantidad</label>
    <td><input type="text" name="CANTIDAD" id='CANTIDAD' 
    onkeyup="operacion(this);"
    /></td>

    <label>Valor</label>
    <td><input type="text" name="VALOR_RE_MO" id='VALOR_RE_MO'/></td>

</table>
    
asked by Anderviver 08.11.2017 в 16:10
source

3 answers

1

According to what I understood, you want to be able to add more rows that contain the fields item , cantidad and valor and that also work as the first row that is already in the table, if so, then I share the following:

A fragment of code, I told you that I did not use jQuery .

function cargar_precio(valor, elemento_html){
    var codigo = '';
    
    switch( valor ){
		    case '':
				    codigo = '';
				break;
				case 'ANCOL':
				    codigo = '100';
				break;
				case 'ARTEL':
						codigo = '200';
				break;
  	}

    //El parametro 'elemento_html' sirve para referenciar al elemento, este es un elemento HTML creado con la función 'agregar_fila'
		if(elemento_html){
        //Si este paramentro existe, entonces la función 'cargar_precio' fue llamada desde una fila agregada desde la función 'agregar_fila'
				elemento_html.value = codigo;
		}
		else{
    document.getElementById('VALOR_RE_MO').value = codigo;
	  }
}

function operacion(cantidad_, valor_, item_){
    //Los parametros 'cantidad_', 'valor_' e 'item_' sirven para referenciar elementos creados desde 'agregar_fila'
    if(cantidad_ && valor_ && item_){
		    cargar_precio( item_.value.toUpperCase(), valor_);

		    var valor = parseInt( valor_.value ),
				    cantidad = parseInt( cantidad_.value );

				if(!isNaN( valor ) && !isNaN( cantidad )){
				    valor_.value = valor * cantidad;
				}
		}
		else{
		    cargar_precio( document.getElementById('ITEM').value.toUpperCase());

				var valor = parseInt( document.getElementById('VALOR_RE_MO').value ),
				    cantidad = parseInt( document.getElementById('CANTIDAD').value );

				if(!isNaN( valor ) && !isNaN( cantidad )){
        document.getElementById('VALOR_RE_MO').value = valor * cantidad;
				}
		}
}

/*
*En la función agregar_fila, se crea una fila con los campos 'item', 'canntidad' y 'valor' y se insertan en la tabla 'PRODUCTOS'
*/
function agregar_fila(){
    var item = document.createElement('input'),
				cantidad = document.createElement('input'),
				valor = document.createElement('input'),
				fila = document.createElement('tr'),
				celda_item = document.createElement('td'),
				celda_cantidad = document.createElement('td'),
				celda_valor = document.createElement('td');

    item.type = 'text';
	  cantidad.type = 'text';
	  valor.type = 'text';

		celda_item.appendChild( item );
		celda_cantidad.appendChild( cantidad );
		celda_valor.appendChild( valor );

		fila.appendChild( celda_item );
		fila.appendChild( celda_cantidad );
		fila.appendChild( celda_valor );

    document.getElementById('PRODUCTOS').getElementsByTagName('tbody')[0].appendChild( fila );

    //Se agrgan los evetos 'onkeyup'
		item.addEventListener('keyup', function(){
    cargar_precio(this.value.toUpperCase(), valor);
		}, false);

		cantidad.addEventListener('keyup', function(){
		    operacion(cantidad, valor, item);
		}, false);
}
<table id="PRODUCTOS">
			<thead>
				<caption>
					Productos <button onclick="agregar_fila()">Agregar</button>
				</caption>
			</thead>
			<tbody>
				<tr>
					<th>Item</th>
					<th>Cantidad</th>
					<th>Valor</th>
				</tr>
				<tr>
					<td>
						<input type="text" name="ITEM" id='ITEM' onkeyup='cargar_precio(this.value.toUpperCase());' autofocus="autofocus" O>
					</td>
					<td>
						<input type="text" name="CANTIDAD" id='CANTIDAD' onkeyup="operacion();" />
					</td>
					<td>
						<input type="text" name="VALOR_RE_MO" id='VALOR_RE_MO' />
					</td>
				</tr>
			</tbody>
		</table>

Sorry I do not give you a more detailed explanation, if you need it write in the comments.

I hope and serve you.

Update:

Responding to your comment @Andersson Viveros Martinez , I'll give you an example that works by cloaking the row and not creating it.

//Ya conoces el funcionamiento de las funciones 'cargar_precio' y 'operacion'
function cargar_precio(valor, elemento_html){
    var codigo = '';

    switch( valor ){
        case '':
            codigo = '';
        break;
        case 'ANCOL':
            codigo = '100';
        break;
        case 'ARTEL':
            codigo = '200';
        break;
    }

    if(elemento_html){
        elemento_html.value = codigo;
    }
    else{
        document.getElementById('VALOR_RE_MO').value = codigo;
    }
}

function operacion(cantidad_, valor_, item_){
    if(cantidad_ && valor_ && item_){
        cargar_precio( item_.value.toUpperCase(), valor_);

        var valor = parseInt( valor_.value ),
            cantidad = parseInt( cantidad_.value );

        if(!isNaN( valor ) && !isNaN( cantidad )){
            valor_.value = valor * cantidad;
        }
    }
    else{
        cargar_precio( document.getElementById('ITEM').value.toUpperCase());

        var valor = parseInt( document.getElementById('VALOR_RE_MO').value ),
            cantidad = parseInt( document.getElementById('CANTIDAD').value );

        if(!isNaN( valor ) && !isNaN( cantidad )){
            document.getElementById('VALOR_RE_MO').value = valor * cantidad;
        }
    }
}

//El parametro 'lista_de_elementos'
//es una especie de 'array' que no es un 'array' sino un 'NodeList' que contiene los elementos 'input'
function remover_atributos( lista_de_elementos ){
    //Con esta función eliminaremos los atributos como 'id', 'name' y 'onkeyup'
    //para que no interfieran con los demas, recuerda que solo puede
    //haber un elemento con un mismo 'id', es decir, el 'id' debe ser unico 
    //para cada elemento dentro del documento HTML.
    for(var i=0, elemento; elemento=lista_de_elementos[i]; i++){
        if(elemento.tagName == 'INPUT'){
            elemento.removeAttribute('id');
            elemento.removeAttribute('name');
            elemento.removeAttribute('onkeyup');

            //Aprovechamos esta función para limpiar el valor
            elemento.value = '';
        }
    }
}

function agregar_fila(){
    var fila = document.getElementById('FILA_INICIAL').cloneNode(true),
        celdas = fila.getElementsByTagName('td');

    //Removemos los atributos de los elementos 'input' que estan dentro de las celdas (td)
    //El atributo o la propiedad 'childNodes' contiene la 'lista' de tipo 'NodeList'
    remover_atributos( celdas[0].childNodes );
    remover_atributos( celdas[1].childNodes );
    remover_atributos( celdas[2].childNodes );


    //Insertamos el elemento clonado a la tabla
    document.getElementById('PRODUCTOS').getElementsByTagName('tbody')[0].appendChild( fila );
    
    //Le damos el 'foco' a el input donde se capturara el 'item'
    celdas[0].getElementsByTagName('input')[0].focus();

    //El primer elemento 'td' es el que contiene el elemento 'input'
    //en el cual se capturara el 'item', agregamos el evento 'onkeyup'
    celdas[0].getElementsByTagName('input')[0].addEventListener('keyup', function(){
        //El elemento "celdas[2].getElementsByTagName('input')[0]" contiene
        //el input en el que se mostrara el valor
        cargar_precio(this.value.toUpperCase(), celdas[2].getElementsByTagName('input')[0]);
    }, false);

    //El segundo elemento 'td' de la fila (tr) contiene el 'input' en el cual
    //se tiene la ingresar la cantidad, en este le agregamos el evento
    //'keyup' para realizar la operacion
    celdas[1].getElementsByTagName('input')[0].addEventListener('keyup', function(){
        //El 1er argumento que recibe 'operacion' es el input en el
        //que se escribira la cantidad, 'this' es ese 'input' en este contexto
        operacion(this, 

                //El 2do argumento que recibe 'operacion' es el input en el cual
                //se mostrara el valor, ese 'input' es 'celdas[2].getElementsByTagName('input')[0]'
                //porque la segunda celda contiene ese 'input'
                  celdas[2].getElementsByTagName('input')[0],

                //El 3er argumento que recibe 'operacion' es el input en el
                //cual se captura el 'item', el cual es 'celdas[0].getElementsByTagName('input')[0]'
                //porque la 1er celda contiene ese 'input'
                  celdas[0].getElementsByTagName('input')[0]);
    }, false);
}
<table id="PRODUCTOS">
    <thead>
        <caption>
            Productos <button onclick="agregar_fila()">Agregar</button>
        </caption>
    </thead>
    <tbody>
        <tr>
            <th>Item</th>
            <th>Cantidad</th>
            <th>Valor</th>
        </tr>
        <!-- Definimos un identificador para poder clonarla usando un identificador -->
        <tr id="FILA_INICIAL">
            <td>
                <input type="text" name="ITEM" id='ITEM' onkeyup='cargar_precio(this.value.toUpperCase());' autofocus="autofocus">
            </td>
            <td>
                <input type="text" name="CANTIDAD" id='CANTIDAD' onkeyup="operacion();" />
            </td>
            <td>
                <input type="text" name="VALOR_RE_MO" id='VALOR_RE_MO' />
            </td>
        </tr>
    </tbody>
</table>

Greetings!

    
answered by 08.11.2017 / 17:20
source
0

I use this function to clone lines of tables:

function AddRemoveRowsAV(){
    var x = 1;
    $('.plusbtnAV').on("click",function() {
        var bindElement =   $(this).attr("bind");
        var x = $("#"+bindElement+" tr").length+1;
        if(x <= 10 ){
            var $clone  = $("#"+bindElement+" tr:last").clone();
            $clone.find('input').each(function(){
                var Cval        =   $(this).val();
                var Cname   =   $(this).attr('name').replace(/\d+/g, '');
                var Cid         =   $(this).prop('id').replace(/\d+/g, '');
                $(this).attr('name', Cname + x);
                $(this).prop('id', Cid + x );
                if($.isNumeric(Cval)){
                    $(this).val(x);
                }else{
                    $(this).val('');
                }
            });
            $clone.find("select").each(function(){
                var Cname   =   $(this).attr('name').replace(/\d+/g, '');
                var Cid         =   $(this).prop('id').replace(/\d+/g, '');
                $(this).attr('name', Cname + x);
                $(this).prop('id', Cid + x );
            });
            $("#"+bindElement).append($clone);
        }else{
            alert("Error: no puede Agregar mas Lineas");
        }
    });
    $('.minusbtnAV').on("click",function() {
        var bindElement =   $(this).attr("bind");
        var x = $("#"+bindElement+" tr").length;
        if(x != 1){
            $("#"+bindElement+" tr:last-child").remove();
            x = x - 1;
        }else{
            alert("Error: no puede Quitar todas las Lineas");
        }
    });
}

You should adapt it to your functions and needs; this function uses Jquery and delegated events: $('.plusbtnAV').on("click",function() { otherwise, if you add content to the DOM, the script will not detect it.

It should also be noted that the system generates the input with auto incremental names based on a pattern.

    
answered by 08.11.2017 в 16:51
-1

Try to clone by passing true to the function.

$("#adicional").on('click', function(){
  $("#tabla tbody tr:eq(0)").clone(true).removeClass('fila-
    fija').appendTo("#tabla");
});
    
answered by 08.11.2017 в 16:58