How to validate a switch (materialize) with jquery?

0

In a ready table the users brought from a database, and to validate that a user is active or inactive, use a SWITCHE (on/off) ...

  .done(function(rest) {
            let resp = $.parseJSON(rest);
            let output = '';
            resp.map((e, key) => {
                // Aqui valido si el usuario esta activo o inactivo
                resp[key]['estado'] != 0 ?  output = "<input type='checkbox' class='item' checked >" : output = "<input type='checkbox' class='item'>";

                    $('.tusers').append('<tr>
                            <td>${resp[key]['codigocurso']}</td>
                            <td>${resp[key]['nombre']}</td>
                            <td>${resp[key]['email']}</td>
                            <td>${resp[key]['id']}</td>
                            <td>
                                <div class='switch' onclick='idUser(${resp[key]['id']})'>
                                    <label>
                                        Inactivo
                                        ${output}
                                        <span class='lever'></span>
                                        Activo
                                    </label>
                                </div>
                            </td>
                            <td><button class='btn waves-light red'>Eliminar</button></td>
                        </tr>');
            })
        })

function idUser(id){
        let checked;
        $(".item").change(function() {

            if($(this).is(":checked")) {
                checked = true;
            }
            else {
                checked = false;
           }

         $.ajax({
            url: 'http://localhost/conexion/controllers/HomeClass.php/updatestate',
            type: 'POST',
            data: {'id': id, 'checked' : checked}
        })
        .done(function(resp) {          
            console.log(resp);
        })
        .fail(function() {
            console.log("error");
        });
        })

  }

PROBLEM When I update the status of a user with the switch, I change the status of all users in different ways.

It can be seen that when changing a switche changes the status of others in the script, how to validate the change of a single switch if it affects others?

    
asked by JDavid 10.07.2018 в 16:38
source

1 answer

2

Here is an example of how you can do what you are trying but instead of using the onclick event, you can add an attribute to each checkbox with its id, then binde the event "change" to these checkboxes and get in the execution of the event the checkbox id and its status.

I hope it helps you!

Greetings!

$(document).ready(function() {

  //Supongamos que a traves de tu ajax te llegan los siguientes datos
  let resp=[
      {
          codigocurso: 1,
          nombre: "pepe",
          email: "[email protected]",
          id: 1
      },
      {
          codigocurso: 2,
          nombre: "pepe2",
          email: "[email protected]",
          id: 2
      }
  ];

  //cuando armas la tabla podes pasarle un "data-id" al checbox
  $.each(resp, function(index,value){
      $('.tusers').append('<tr>
      <td>${value['codigocurso']}</td>
      <td>${value['nombre']}</td>
      <td>${value['email']}</td>
      <td>${value['id']}</td>
      <td>
          <div class="switch">
              <label>
                  <input type="checkbox" data-id="${value['id']}"> //<- aca el "data-id"
                  <span class="lever"></span>
              </label>
          </div>
      </td>
      <td><button class="btn waves-light red">Eliminar</button></td>
      </tr>');
  });
  
  //luego bindeas el evento change a los checkbox, y obtenes el id del checkbox que se modifico en la ejecucion de cada evento
  $(".switch").find("input[type=checkbox]").on("change",function() {
      let checked = $(this).prop('checked');
      let id = $(this).data('id');
      console.log(id, checked);
      
      // de aca en adelante haces lo necesario con el codigo 
      /*
      $.ajax({
          url: 'http://localhost/conexion/controllers/HomeClass.php/updatestate',
          type: 'POST',
          data: {'id': id, 'checked' : checked}
      })
      .done(function(resp) {          
          console.log(resp);
      })
      .fail(function() {
          console.log("error");
      });
      */
      
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet"/>


<table class="tusers">
</table>
    
answered by 10.07.2018 / 19:33
source