By clicking on a checkbox jquery only works if there is an alert

1

I have a checkbox list, the user selects the ones of their preference and then presses a button and they are saved.

$('#GuardarPermisos').on('click', function () {
   Guardar();
}

This I want to change to that every time you click on a checkbox you save the selection without having to press the button.

The generated checkboxes have a class, with which I do the following:

$('.tiposas').on('click', function () {
    alert('a');
});'

Each click on one must perform an action, but it does not work unless you put an alert before the event.

$(document).ready(function () {
   alert('con este alert si funciona')';
   $('.tiposas').on('click', function () {
   alert('a');
   });
});

I do not know what I'm doing wrong, I hope you can help me

Thank you.

    
asked by LoganFenix 22.08.2018 в 18:23
source

5 answers

1

At certain times when you speak directly to the selectors it does not work, I in particular speak to the DOM to force you to search wherever you are, I leave you an example

//Es lo mismo que document.ready, pero mas cordo
$(function(){

//Aquí es donde te digo que le hablo al document, le ligo el evento, le digo que selectores y le paso lo que quiero que haga
$( document ).on( 'click', '.foo', function(){
let val = $(this).val();
  //Revisa en que status está el checkbox y controlalo según lo //desees
  if( $( this ).is( ':checked' ) ){
    alert( 'Guardando información de '+ val +'...' );
  }
  
  else{
    alert( 'Desguardando información de ' + val + '...' );
  }
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Foo<input type="checkbox" class="foo" value="Foo">
Bar<input type="checkbox" class="foo" value="Bar">
Poo<input type="checkbox" class="foo" value="Poo">
Nee<input type="checkbox" class="foo" value="Nee">
Lol<input type="checkbox" class="foo" value="Lol">

I hope you serve

    
answered by 22.08.2018 / 18:47
source
1

There are several methods to do what you want and for this you need to verify that the checkboxes are selected here an example

$(document).ready(function(){

$( '.mycheckbox' ).on( 'click', function() {
    if( $(this).is(':checked') ){
        // Hacer algo si el checkbox ha sido seleccionado
        alert("El checkbox con valor " + $(this).val() + " ha sido seleccionado");
    } else {
        // Hacer algo si el checkbox ha sido deseleccionado
        alert("El checkbox con valor " + $(this).val() + " ha sido deseleccionado");
    }
});
})
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" class="mycheckbox">
    
answered by 22.08.2018 в 18:35
1

Remove a quote on the line where the alert.

After closing the last parenthesis, your code should look something like this by removing the alert :

   $(document).ready(function () {
      $('.tiposas').on('click', function () {
      alert('a');
      });
    });
    
answered by 22.08.2018 в 18:56
0

As Rene told you, you have one more quote, your code should be like this:

$(document).ready(function () {
   alert('con este alert si funciona');
   $('.tiposas').on('click', function () {
   alert('a');
   });
});

To save by pressing the checkbox, check if checked

$(".check").on("click", function(){
  if($(this).is(":checked")){
    alert('Guardado');
    //Aquí colocas tu función guardar();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='checkbox' class='check'>Checkbox 1</input>
<input type='checkbox' class='check'>Checkbox 2</input>
<input type='checkbox' class='check'>Checkbox 3</input>
    
answered by 22.08.2018 в 18:41
0

Alternative using the event change and a little bit of ES6

let laLista = [];

let ponerElemento = (v) => {
  laLista.push(v);
}
let borraElemento = (v) => {
  laLista = laLista.filter(e => e !== v);
}
/* 
// forma tradicional
let borraElemento = (v) => {
  let i = laLista.indexOf(v);
  if (i > -1) {
    laLista.splice(i, 1);
  }
}
//*/
document.addEventListener('DOMContentLoaded', function() {

  const checkboxes = document.getElementsByClassName('foo');

  [...checkboxes].forEach((el) => {
    el.addEventListener('change', (ev) => {
      if (ev.target.checked) {
        ponerElemento(ev.target.value);
        consolog(ev.target.value, 'checked', "Lista:", laLista)
      } else {
        borraElemento(ev.target.value);
        consolog(ev.target.value, 'not checked', "Lista:", laLista)
      }
    })
  })

});


// para que el log no tape las cosas
var consolog = function(...cosas) {
  var logs = document.getElementById('logs');
  cosas.forEach((t) => {
    logs.innerHTML += t + " ";
  });
  logs.innerHTML += "\n";
  logs.scrollTop = logs.scrollHeight;

};
#logs {
  height: 11em;
  overflow-y: scroll;
  min-width: 50vw;
  background: #fafafa;
  position: fixed;
  right: 0;
  top: 0;
}
Foo
<input type="checkbox" class="foo" value="Foo">
<br> Bar
<input type="checkbox" class="foo" value="Bar">
<br> Poo
<input type="checkbox" class="foo" value="Poo">
<br> Nee
<input type="checkbox" class="foo" value="Nee">
<br> Lol
<input type="checkbox" class="foo" value="Lol">

<PRE id="logs"></PRE>
    
answered by 23.08.2018 в 01:09