Find row in datatable by 2-column value attribute

0

I have a datatable to which I add rows dynamically from 2 combos by means of js, in this way a row is generated with the 2 descriptions of the combos and in the value of the td I assign the id of the values of the combos, that is getting complicated is to validate that combos combination can not add 2 times, but I do not know how to validate looking for those values within the datable.

    
asked by Hector Scesa 14.08.2017 в 21:57
source

2 answers

0

I have solved it in the following way, passing the array and the object by parameter to a function that validates comparing each one of the properties.

 existeEnArray = function (array,obj) {
       var i;

       array.map(function (data, index) {
           if (data.prop1 === obj.prop1 && data.prop2 === obj.prop2) {
               i = index;
           }
       })

       if (i === undefined) {
           return false;
       }

       return true;
   }
    
answered by 17.08.2017 / 16:53
source
0
    <html>
    <head>

    </head>
    <body>
    <table id="table">
       <tr><th>Paises</th><th>Ciudad</th></tr>
       <tr><td value="2">Cuba</td><td value="5">Habana</td></tr>
    </table>
    <script type="text/javascript">
       //Verifica que exta una columna de la tabla con el valor pasado como 2do parámetro  
       function contiene(tabla_id, val){
            //Obtiene la tabla dado su id
            var tabla = document.getElementById(tabla_id);
            //obtiene todas las celdas de la tabla
            var tds = document.getElementsByTagName("td");
            //Crea y asigna la variable que se retornará
            var resultado = false;
            //recorre las celdas de la tabla
            for(var i=0;i<tds.length;i++){
                //Si encuentra una con el atributo value y su valor es igual al que se esta buscando....
                if(getAttr(tds[i],"value") == val){
                   //Asigna a verdadero la variable a retornar
                   resultado = true;
                   //Sale del ciclo
                   break;
                }
            }
            return resultado;
       }

       //Función que devuelve el valor de un atributo en un elemento HTML si el atributo existe, sino devolvera null
       function getAttr(elemento, nombre){
          //Inicializo a null la variable a retornar
          var resultado = null;
          //Recorro los atributos del elemento pasado por parámetro
          for(var j=0;j<elemento.attributes.length;j++){
                //Si el nombre del atributo coincide con el ke estamos buscando...
                if(elemento.attributes[j].name === nombre)
                {
                   //Asigno su valor a la variable que retornaré
                   resultado = elemento.attributes[j].value;
                   //Salgo del ciclo porque ya encontré lo que buscaba
                   break;
                }
            }
            return resultado;
       }

       //Con estas líneas es que puedes comprobar que exista o no el valor antes de ingresarlo, si existe muestras un mensaje , sino añades las celdas a tu datatable
        if(contiene("table",7))
            alert("ya existe");
        else
            //Aqui iría las líneas de tu código donde insertas la descripción extraida de los combobox
            alert("no existe");

        //Si quieres comparar los valores por el contenido de los combobox el segundo parámetro de la función contiene es el ke necesitarias cambiar
        //Quedaría mas o menos así
        //var combo1 = document.getElementById("combo1");
        //if(contiene("table",combo1.value))
        //  alert("ya existe")
        //else
        //  Codigo de Añadir celdas
    </script>
    </body>
    </html>

If you want to do it with jquery I can tell you that you avoid more than 10 lines of code is simpler, I know that dataTable is a jquery plugin but I do not know if you wanted to do it with normal javaascript or using that library, if it is the second You tell me and I'll give you the example too.

    
answered by 16.08.2017 в 15:16