inputs and checkbox insertion selection

0

Greetings I have a problem I am trying to enable Inputs as you select checkbox, the problem is that they are checkboxes shown by a while which comes from the database. Below I show the code.

<div class="campo clearfix">
      <label for="herram" id="herra">Selecionar herramientas:</label><br/>
        <?php
          try {
            $sql = "SELECT * FROM herramienta";
            $res_herram = $conn->query($sql);
            $total_h = $res_herram->num_rows;
            $i = 0;
            while ($herram = $res_herram->fetch_assoc()) {
              echo '<div class="contenido_dia">';
            echo '<input type="checkbox" id='"checkh" . $herram['id_herra'] . ' name="herram[]"  value=' . $herram['id_herra'] . '> ' . $herram['nom_herra'] . " " ;
            echo '<input type="number" min="0" max="5" disabled="disabled" id='"canth". $herram['id_herra'] . ' size="1" name="herram_cant[]" placeholder="0">' . '<br/>';
            echo '</div>';
            $i++;
            }
          } catch (Exception $error) {
            echo "Error:" . $error->getMessage();
          }
        ?>
    </div>

I was trying with this javascript but I think this is very bad

for (var i = 0; i < 9; i++) {
$("#checkh" + i).change(function(){
var comentario = $( '#canth' +i, $(this).parents ('div'));
if( $(this.checked)){
  comentario.removeAttr('disabled');
  } else {
  comentario.attr('disabled', true);
  }
 });
}
    
asked by J. Medina 06.12.2017 в 01:08
source

1 answer

0

Instead of creating a trigger for each checkbox with its id, it is better to create one for all checkboxes contained within the div.campo without taking into account how many there is or the id that each one has.

When the trigger is executed you just have to select the next input of type number and activate or deactivate it as you need.

To activate and deactivate inputs with jQuery it is recommended to use the .prop() method.

Javascript:

$('div.campo').on('change', 'input[type=checkbox]', function() {

  if ($(this).prop('checked')) {
    $(this).next('input[type=number]').prop('disabled', false);
  } else {
    $(this).next('input[type=number]').prop('disabled', true);
  }

});
    
answered by 06.12.2017 / 10:04
source