Clone dependent selects in 3 levels

1

I have a code in which I cloned the first row of a table using a "+" button, which has three select each dependent on the other, that is, depending on what I select in the first select (soc), it will list me some options in the second (term), and in turn it will list me some options in the second (degree), although it does not copy the select , and the options are displayed well only if it is the first row , and that's the problem, when I clone a row, and I'm going to select one of the options of the first select ok, but when I'm going to select the second one it calls me the options of select of the top row in (term ) and (grade), I do not know what to do because I know that if you clone the row, these are the codes:

FORM

<html>
   <head>
   </head>
   <body>
      <table align="center" class="table bg-info" id="tabla">
         <!---Campo CTCAE v4.0 SOC-->
         <thead>
            <tr>
               <th>SOC</th>
               <th>TERM</th>
               <th>GRADO</th>
            </tr>
         </thead>
         <tbody>
            <!---Campo CTCAE v4.0 SOC-->
            <tr class="fila-fija">
               <td>
                  <select id="soc" name="soc[]">
                     <option value="NULL">SELECCIONA...</option>
                     <option value="Blood ">Blood</option>
                     <option value="Cardiac">Cardiac</option>
                     <option value="Congenital">Congenital</option>
                     <option value="Ear and labyrinth disorders">Ear and labyrinth disorders</option>
                     <option value="Endocrine disorders">Endocrine disorders</option>
                     <option value="Eye disorders">Eye disorders</option>
                     <option value="Gastrointestinal disorders">Gastrointestinal disorders</option>
                     <option value="General disorders and administration site conditions">General disorders and administration site conditions</option>
                     <option value="Hepatobiliary disorders">Hepatobiliary disorders</option>
                     <option value="Immune system disorders">Immune system disorders</option>
                     <option value="Infections">Infections and infestations</option>
                     <option value="Injury">Injury</option>
                     <option value="Investigations">Investigations</option>
                     <option value="Metabolism">Metabolism</option>
                     <option value="Musculoskeletal">Musculoskeletal</option>
                     <option value="Neoplasms benign, malignant and unspecified">Neoplasms </option>
                     <option value="Nervous system disorders">Nervous system disorders</option>
                     <option value="Pregnancy">Pregnancy</option>
                     <option value="Psychiatric disorders">Psychiatric disorders</option>
                     <option value="Renal and urinary disorders">Renal and urinary disorders</option>
                     <option value="Reproductive system">Reproductive system</option>
                     <option value="Respiratory">Respiratory</option>
                     <option value="Skin ">Skin </option>
                     <option value="Surgical ">Surgical </option>
                     <option value="Vascular disorders">Vascular disorders</option>
                  </select>
               </td>
               <!---Campo CTCAE v4.0 Term-->
               <td><select name="term[]" id="term"></select></td>
               <!---Campo CTCAE Grado-->
               <td><select name="grado[]" id="grado"></select></td>
               <td class="eliminar"><input type="button" value="-"/></td>
            </tr>
         </tbody>
      </table>
      <div class="btn-der"><button id="adicional" name="adicional" type="button" class="btn btn-warning">+</button></div>
   </body>
</html>

CODE TO CLONATE

<script type="text/javascript" src="Js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<?php require('Includes/getPrueba.php'); ?>


<script>
  $(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(true).removeClass('fila-fija').appendTo("#tabla tbody");

});

  $(document).on("click",".eliminar",function(){
      var parent = $(this).parents().get(0);
      $(parent).remove();
  });

  });
</script>

CODE IN AJAX FOR THE ARRAY

<script type="text/javascript" >
$(document).ready(function(){
    $("#soc").change(function(){
            //alert($('select[name=soc]').val());
            $("#soc option:selected").each(function () {
            soc = $(this).val();
            $.post("Includes/getTermPrueba.php", { soc: soc}, 
                    g    function(data){
                            $("#term").html(data);
            });
        });  
   })
}); 

$(document).ready(function(){
    $("#term").change(function(){
            //alert($('select[name=soc]').val());
            $("#term option:selected").each(function () {
            term = $(this).val();
            $.post("Includes/getGrado.php", { term: term }, 
                         function(data){
                            $("#grado").html(data);
            });
        });  
   })
});


</script>

EXAMPLE [! [In the first nesting everything is fine ...] [1]] [1] [! [But when you hit the little button "+" if you add them again, however the select 2 and 3 are left with the same options as the first one that was chosen.] [2]] [2] [! [And so it does not matter what amount is added or removed.] [3]] [3]

MODIFICATION OF CODE I have listened to their corrections, likewise staying as the following ... but still not working: (

FORM

    <html>
<head>

<script type="text/javascript" src="Js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<?php require('Includes/getPrueba.php'); ?>


<script>
  $(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(true).removeClass('fila-fija').appendTo("#tabla tbody");
});

  $(document).on("click",".eliminar",function(){
      var parent = $(this).parents().get(0);
      $(parent).remove();
  });

  });
</script>

</head>

<body>
<table align="center" class="table bg-info" id="tabla">
 <!---Campo CTCAE v4.0 SOC-->
<thead>
 <tr>
  <th>SOC</th>
  <th>TERM</th>
  <th>GRADO</th>
 </tr>
</thead>

<tbody>
 <!---Campo CTCAE v4.0 SOC-->
 <tr>
<td>
<select class="soc" id="soc" name="soc[]">
<option value="NULL">SELECCIONA...</option>
<option value="Blood and lymphatic system disorders">Blood and lymphatic system disorders</option>
<option value="Cardiac disorders">Cardiac disorders</option>
<option value="Congenital, familial and genetic disorders">Congenital, familial and genetic disorders</option>
<option value="Ear and labyrinth disorders">Ear and labyrinth disorders</option>
<option value="Endocrine disorders">Endocrine disorders</option>
<option value="Eye disorders">Eye disorders</option>
<option value="Gastrointestinal disorders">Gastrointestinal disorders</option>
<option value="Nervous system disorders">Nervous system disorders</option>
<option value="Pregnancy, puerperium and perinatal conditions">Pregnancy, puerperium and perinatal conditions</option>
<option value="Psychiatric disorders">Psychiatric disorders</option>
<option value="Renal and urinary disorders">Renal and urinary disorders</option>
<option value="Vascular disorders">Vascular disorders</option>
</select>
 </td>
  <!---Campo CTCAE v4.0 Term-->
 <td><select name="term[]" id="term" class="term"></select></td>
<!---Campo CTCAE Grado-->
 <td><select name="grado[]" id="grado" class="grado"></select></td>

 <td class="eliminar"><input type="button" value="-"/></td>
</tr>
</tbody>
</table>

<div class="btn-der">
  <button id="adicional" name="adicional" type="button" class="btn btn-warning">+</button>
</div>

</body>
</html>

BRING SELECT OPTIONS

<script type="text/javascript" >
$(document).ready(function(){

    $(".soc").change(function(){
            var tr =  $(this).parent().parent();
            alert($('.soc').val());
            soc = $(this).val();
            $.post("Includes/getTerm.php", { soc: soc }, 
                         function(data){
                            $("#term").html(data);
            });
   })

    $(".term").change(function(){
            alert($('.term').val());
            var tr =  $(this).parent().parent();
            term = $(this).val();
            $.post("Includes/getGrado.php", { term: term }, 
                         function(data){
                            $("#grado").html(data);
            });  
   })

});
</script>

LOAD TERM

<?php
require('../conexion.php');
  $soc = $_POST['soc'];

$sqlT = "select term from dbo.ctcae  where soc='$soc'";
$resultadoT = sqlsrv_query( $conn, $sqlT );


$html = "<option value=''>SELECCIONA...</option>";

while($rowT = sqlsrv_fetch_array( $resultadoT, SQLSRV_FETCH_ASSOC) )  {
$html.= "<option value='".$rowT['term']."'>".$rowT['term']."</option>";
} 

echo $html;

?>

LOAD GRADE

 <?php
    require ('../conexion.php');

    $term = $_POST['term'];

$sqlG = "select grado1, grado2, grado3, grado4, grado5 from dbo.ctcae  where term='$term'";
$resultadoG = sqlsrv_query( $conn, $sqlG );

while($rowG = sqlsrv_fetch_array( $resultadoG, SQLSRV_FETCH_ASSOC) )  {
        $html.= "<option value='".$rowG['grado1']."'>".$rowG['grado1']."</option>";
        $html.= "<option value='".$rowG['grado2']."'>".$rowG['grado2']."</option>";
        $html.= "<option value='".$rowG['grado3']."'>".$rowG['grado3']."</option>";
        $html.= "<option value='".$rowG['grado4']."'>".$rowG['grado4']."</option>";
        $html.= "<option value='".$rowG['grado5']."'>".$rowG['grado5']."</option>";
    }
    echo $html;
?>

The first one is fine, but when I press the little button "+" it adds another select, but this one gets completely out of control, keeps bringing the opc of the last select ....

All options are out of control, the 2nd selection affects the first and the options that were already chosen are deleted ...

I do not know if it has anything to do with BD from where I throw my options:

NEW ERROR! Perfect, although the error persists in that if you add another option the part of degree is still selected as if it were the first select ....

When selecting the new option in this case "Cardiac" appears to me as if it had the values of the past ...

Although if it changes, the options correspond to "cardiac" ...

The problem is that although the options change each one with their respective, I drag the values of the first of, then to save it in the BD all will be saved with the same value.

    
asked by Jaqueline Duran 23.03.2018 в 17:14
source

2 answers

1

Explanation of Error

The error lies in the assignment of the function .change() since you do it by selecting the id of an element $("#soc").change() . By doing that, you will only recognize the action of the first element that you find with that id, so when you click on your first cloned select it changes the second select of the tr that you cloned because in this line $("#soc option:selected") points to that element.

Solution

To solve the error, you would have to change the logic of how you do the change() events by pointing it towards class selectors that you will add to your select. On the other hand, in order not to confuse the aggregation of the html to the side select you will perform a search in an html block in which only the select is with that id, for this you will be located in the tr where you will do a find() . As a suggestion, do not use each() for a single action.

Edited Solution

With the changes you made, you only need to add the reference to which select you want to do in the part where you set the html. In the function $.post() you must add the example change that I put below.

<script type="text/javascript" >
$(document).ready(function(){

    $(".soc").change(function(){
            var tr =  $(this).parent().parent();
            alert($('.soc').val());
            soc = $(this).val();
            $.post("Includes/getTerm.php", { soc: soc }, 
                         function(data){
                            //esta linea se modifica  para buscar 
                            //el select del  tr donde estas
                            tr.find("#term").html(data); 
            });
   })

    $(".term").change(function(){
            alert($('.term').val());
            var tr =  $(this).parent().parent();
            term = $(this).val();
            $.post("Includes/getGrado.php", { term: term }, 
                         function(data){
                            //esta linea se modifica  para buscar 
                            //el select del  tr donde estas
                            tr.find("#grado").html(data);
            });  
   })

});
</script>

Similar solution

$(function() {
  // Clona la fila oculta que tiene los campos base, y la agrega al final de la tabla
  $("#adicional").on('click', function() {
    var tr = $("#tabla tbody tr:eq(0)").clone(true).removeClass('fila-fija');
    tr.find("#term").empty(); //aqui se limpia el select term
    tr.find("#grado").empty(); //aqui se limpia el select grado
    tr.appendTo("#tabla tbody"); // agregas el row clonado a la tabla
  });

  $(document).on("click", ".eliminar", function() {
    var parent = $(this).parents().get(0);
    $(parent).remove();
  });

  $(".soc").change(function() { //esta parte se cambiara a que haga la funcion en los los select de class soc
    var tr =  $(this).parent().parent(); //obtenemos el tr padre para hacer la busqueda
    
    //El each esta demas
    //select.find("#soc option:selected").each(function() {
      soc = $(this).val();
      
      //comento tu post solo como de ejemplo
      //$.post("Includes/getTermPrueba.php", {
      //    soc: soc
      //  },

      //   function(data) {
      //aqui buscamos solo en tr al select por el id
       tr.find("#term").html( '<option value="Respiratory">Respiratory</option>' 
                      + '<option value="Skin ">Skin </option>'
                      + '<option value="Surgical ">Surgical </option>'
                      + '<option value="Vascular disorders">Vascular disorders</option>');
      //   });
    //});
  })

  $(".term").change(function() { //esta parte se cambiara a que haga la funcion en los los select de class term

    var tr =  $(this).parent().parent(); // tr padre para hacer la busqueda
    //$("#term option:selected").each(function() {
      term = $(this).val();
      //$.post("Includes/getGrado.php", {
      //    term: term
      //  },
      //  function(data) {
        tr.find("#grado").html('<option value="Respiratory">Respiratory</option>' 
                      + '<option value="Skin ">Skin </option>'
                      + '<option value="Surgical ">Surgical </option>'
                      + '<option value="Vascular disorders">Vascular disorders</option>');
      //});
    //});
  })
});
<html>

<head>
</head>

<body>
  <table align="center" class="table bg-info" id="tabla">
    <!---Campo CTCAE v4.0 SOC-->
    <thead>
      <tr>
        <th>SOC</th>
        <th>TERM</th>
        <th>GRADO</th>
      </tr>
    </thead>
    <tbody>
      <!---Campo CTCAE v4.0 SOC-->
      <tr class="fila-fija">
        <td>
          <select id="soc" name="soc[]" class="soc">
                     <option value="NULL">SELECCIONA...</option>
                     <option value="Blood ">Blood</option>
                     <option value="Cardiac">Cardiac</option>
                     <option value="Congenital">Congenital</option>
                     <option value="Ear and labyrinth disorders">Ear and labyrinth disorders</option>
                     <option value="Endocrine disorders">Endocrine disorders</option>
                     <option value="Eye disorders">Eye disorders</option>
                     <option value="Gastrointestinal disorders">Gastrointestinal disorders</option>
                     <option value="General disorders and administration site conditions">General disorders and administration site conditions</option>
                     <option value="Hepatobiliary disorders">Hepatobiliary disorders</option>
                     <option value="Immune system disorders">Immune system disorders</option>
                     <option value="Infections">Infections and infestations</option>
                     <option value="Injury">Injury</option>
                     <option value="Investigations">Investigations</option>
                     <option value="Metabolism">Metabolism</option>
                     <option value="Musculoskeletal">Musculoskeletal</option>
                     <option value="Neoplasms benign, malignant and unspecified">Neoplasms </option>
                     <option value="Nervous system disorders">Nervous system disorders</option>
                     <option value="Pregnancy">Pregnancy</option>
                     <option value="Psychiatric disorders">Psychiatric disorders</option>
                     <option value="Renal and urinary disorders">Renal and urinary disorders</option>
                     <option value="Reproductive system">Reproductive system</option>
                     <option value="Respiratory">Respiratory</option>
                     <option value="Skin ">Skin </option>
                     <option value="Surgical ">Surgical </option>
                     <option value="Vascular disorders">Vascular disorders</option>
                  </select>
        </td>
        <!---Campo CTCAE v4.0 Term-->
        <td><select name="term[]" id="term" class="term"></select></td>
        <!---Campo CTCAE Grado-->
        <td><select name="grado[]" id="grado"></select></td>
        <td class="eliminar"><input type="button" value="-" /></td>
      </tr>
    </tbody>
  </table>
  <div class="btn-der"><button id="adicional" name="adicional" type="button" class="btn btn-warning">+</button></div>
</body>

</html>

<script type="text/javascript" src="Js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
    
answered by 23.03.2018 / 18:10
source
1

First to the select you must identify them with class and not with id , the ids are to identify unique elements and you are cloning selects so they are no longer unique.

On the other hand, when you do the events change of each select, you have to find the corresponding select to add the answer that returns you post.

Example, where $ (this) is the selected option:

$(this).closest("tr").find(".grado").html(respuesta);

On the other hand when you add a new row to the table you can delete the contents of the selects in the row that you are cloning

Example, being row a variable where we keep the tr that we just cloned:

row.find('.term').empty(); //vacias el select
row.find('.grado').empty(); //vacias el select

I leave an example working with these changes that I propose, I hope you find it useful.

Greetings!

$(document).ready(function(){

    $(".soc").on("change", function(){
      //llamada a post con $(this).val()
      //suponiendo respuesta "var respuesta"
       var respuesta = '<option value=""></option><option value="test">test</option>';
       $(this).closest("tr").find(".term").html(respuesta);
    });

    $(".term").on("change", function(){
      //llamada a post con $(this).val()
      //suponiendo respuesta "var respuesta"
      var respuesta = '<option value=""></option><option value="test2">test2</option>';
      $(this).closest("tr").find(".grado").html(respuesta);
    });
    
    $("#adicional").on('click', function(){
      var row = $("#tabla tbody tr:eq(0)").clone(true).removeClass('fila-fija');
      row.find('.term').empty(); //vacias el select
      row.find('.grado').empty(); //vacias el select
      row.appendTo("#tabla tbody")
    });
    
    $(".eliminar").on("click",function(){
      var parent = $(this).closest("tr").remove();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
   <head>
   </head>
   <body>
      <table align="center" class="table bg-info" id="tabla">
         <!---Campo CTCAE v4.0 SOC-->
         <thead>
            <tr>
               <th>SOC</th>
               <th>TERM</th>
               <th>GRADO</th>
            </tr>
         </thead>
         <tbody>
            <!---Campo CTCAE v4.0 SOC-->
            <tr class="fila-fija">
               <td>
                  <select class="soc" name="soc[]">
                     <option value="NULL">SELECCIONA...</option>
                     <option value="Blood ">Blood</option>
                     <option value="Cardiac">Cardiac</option>
                     <option value="Congenital">Congenital</option>
                  </select>
               </td>
               <!---Campo CTCAE v4.0 Term-->
               <td><select name="term[]" class="term"></select></td>
               <!---Campo CTCAE Grado-->
               <td><select name="grado[]" class="grado"></select></td>
               <td class="eliminar"><input type="button" value="-"/></td>
            </tr>
            <tr class="fila-fija">
               <td>
                  <select class="soc" name="soc[]">
                     <option value="NULL">SELECCIONA...</option>
                     <option value="Blood ">Blood</option>
                     <option value="Cardiac">Cardiac</option>
                     <option value="Congenital">Congenital</option>
                  </select>
               </td>
               <!---Campo CTCAE v4.0 Term-->
               <td><select name="term[]" class="term"></select></td>
               <!---Campo CTCAE Grado-->
               <td><select name="grado[]" class="grado"></select></td>
               <td class="eliminar"><input type="button" value="-"/></td>
            </tr>
         </tbody>
      </table>
      <div class="btn-der"><button id="adicional" name="adicional" type="button" class="btn btn-warning">+</button></div>
   </body>
</html>

EDIT

Edit based on your last modification, if you change this it should work:

$(".soc").change(function(){

    soc = $(this).val();

    $.post("Includes/getTerm.php", { soc: soc }, 
         function(data){
             $(this).closest("tr").find(".term").html(data);
    });
})

$(".term").change(function(){

    term = $(this).val();

    $.post("Includes/getGrado.php", { term: term }, 
         function(data){
            $(this).closest("tr").find(".grado").html(data);
    });  
})
    
answered by 23.03.2018 в 18:49