How to change the value of the checkbox with jquery

3

How do I change the value of checkbox when it is selected?

Code done so far it shows me object.

$("#checkbox").change(function(){
  var atual = $("#checkbox").val();
     $("p").text(atual); // vamus supor que aqui o valor seja 23
  var troca = $("input[type=checkbox]:checked").val("2"); // quando eu faço isso gostaria que ele alterece o valor daquele checkbox para 2
     $("p").text(troca);
});
    
asked by anonymous 10.06.2016 / 13:53

2 answers

2

As you are working with ID selector, the code below is just for a checkbox.

$(document).ready(function() {
  $('input[id="checkbox"]').on('change', function() {
    $(this).val(2);
    alert($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label><inputtype="checkbox" id="checkbox" value="22">OIE
</label>
    
10.06.2016 / 14:27
1

Use $ (this) to make things easier and switch id to classes as selector.

$(".chkcl").change(function(){

  var atual = $(this).val();
  alert(atual);
  var troca = 2;
  $(this).val(troca); // quando eu faço isso gostaria que ele alterece o valor daquele checkbox para 2
  alert($(this).val());
});

See the working example here .

If you use the Chrome debugger, you'll see that the value has changed dynamically:

    
10.06.2016 / 14:34