Pass parameters

Asked

Viewed 42 times

0

I am developing a system and I need to create an on/off button to update information in the database, but I need to pass the parameter ID by clicking the button to do the update, basically the functioning of the button is this, the problem is that I can’t pass the id to the js script

    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<input id="toggle-event" type="checkbox" id="32" value="32" data-toggle="toggle">
<div id="console-event"></div>

  $(function() {
    $('#toggle-event').change(function() {
      $('#console-event').html('Toggle: ' + $(this).prop('checked'))
    })
  })
inserir a descrição da imagem aqui

1 answer

2


You’re using twice the id in the same element:

<input id="toggle-event" type="checkbox" id="32" value="32" data-toggle="toggle">
       ↑                                 ↑

There are two things to consider:

  1. Doesn’t need (and can’t) a id="toggle-event", otherwise it will repeat on the other buttons in the list, and repeating id’s is incorrect in HTML.

  2. You don’t need one either id="32", since there is a value with the same value. Then just leave only the value and change the id="toggle-event" for class="toggle-event" (class can be repeated). Will be:

<input class="toggle-event" type="checkbox" value="32" data-toggle="toggle">

And in Event Handler, you change the selector # for . and takes the value of the button that triggered the event change with this.value:

$(function() {
   $('.toggle-event').change(function() {
      $('#console-event').html('Toggle: ' + $(this).prop('checked'))
      var valor = this.value;
   })
});

Example:

$(function() {
   $('.toggle-event').change(function() {
      $('#console-event').html('Toggle: ' + $(this).prop('checked'))
      var valor = this.value;
      console.clear(); // limpa o console
      console.log(valor);
   })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<input class="toggle-event" type="checkbox" value="32" data-toggle="toggle">
<br>
<input class="toggle-event" type="checkbox" value="100" data-toggle="toggle">
<div id="console-event"></div>

  • worked perfectly thank you very much, saved my day :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.