si la casilla de verificación está marcada, haga esto


Cuando marque una casilla de verificación, quiero que gire <p> #0099ff.

Cuando desmarque la casilla de verificación, quiero que deshaga eso.

Código que tengo hasta ahora:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 
Author: John Slegers, 2010-11-22

11 answers

Yo uso .change() y this.checked:

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

Sobre el uso this.checked
Andy E ha hecho un gran artículo sobre cómo tendemos a abusar de jQuery: Utilizando el impresionante poder de jQuery para acceder a las propiedades de un elemento. El artículo trata específicamente el uso de .attr("id") pero en el caso de que #checkbox es un <input type="checkbox" /> elemento el problema es el mismo para $(...).attr('checked') (o incluso $(...).is(':checked')) vs this.checked.

 230
Author: jensgram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:02

Prueba esto.

$('#checkbox').click(function(){
    if (this.checked) {
        $('p').css('color', '#0099ff')
    }
}) 

A veces nos excedemos jquery. Muchas cosas se pueden lograr usando jquery con javascript simple.

 47
Author: Chinmayee G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-22 08:26:53

Puede suceder que "esto.marcado "siempre está "activado". Por lo tanto, recomiendo:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});
 31
Author: Benny Neugebauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 20:05:30

Es mejor si defines una clase con un color diferente, entonces cambias la clase

$('#checkbox').click(function(){
    var chk = $(this);
    $('p').toggleClass('selected', chk.attr('checked'));
}) 

De esta manera su código es más limpio porque no tiene que especificar todas las propiedades css (digamos que desea agregar un borde, un estilo de texto u otro...) pero usted acaba de cambiar una clase

 21
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-22 09:03:12

Encontré una solución loca para lidiar con este problema de la casilla de verificación no marcada o marcada aquí está mi algoritmo... crear una variable global digamos var check_holder

Check_holder tiene 3 estados

  1. estado indefinido
  2. 0 estado
  3. 1 estado

Si se hace clic en la casilla de verificación,

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

El código anterior se puede usar en muchas situaciones para averiguar si se ha marcado o no una casilla de verificación comprobar. El concepto detrás de él es guardar los estados de casilla de verificación en una variable, es decir,cuando está activado, desactivado. espero que la lógica pueda ser utilizada para resolver su problema.

 4
Author: zedecliff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 14:35:14

Compruebe este código:

<!-- script to check whether checkbox checked or not using prop function -->
<script>
$('#change_password').click(function(){
    if($(this).prop("checked") == true){ //can also use $(this).prop("checked") which will return a boolean.
        alert("checked");
    }
    else if($(this).prop("checked") == false){
        alert("Checkbox is unchecked.");
    }
});
</script>
 3
Author: Prabhjit Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-24 14:36:18
$('#checkbox').change(function(){
   (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});
 1
Author: Klaster_1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-22 08:27:50

Probablemente usted puede ir con este código para tomar acciones como la casilla de verificación está marcada o desmarcada.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});
 1
Author: Sanjiv Malviya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-03 13:37:49

Yo haría:

$('#checkbox').on("change", function (e){ 

    if(this.checked){

      // Do one thing 

    }

    else{

     // Do some other thing

    }

});

Véase: https://www.w3schools.com/jsref/prop_checkbox_checked.asp

 1
Author: Jon Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 11:48:32

Aplicación Óptima

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});

Demo

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input id="checkbox" type="checkbox" /> 
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
    eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
    Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu
    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.
</p>
 0
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-03 13:51:32

¿Por qué no usar los eventos incorporados?

$('#checkbox').click(function(e){
    if(e.target.checked) {
     // code to run if checked
        console.log('Checked');

     } else {

     //code to run if unchecked
        console.log('Unchecked');
     }
});
 0
Author: Paul 501,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-25 13:30:57