How to exchange the checkbox value with jquery

Asked

Viewed 1,706 times

3

How do I exchange the value of checkbox when he 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);
});
  • You want to exchange the value or text ?

  • I want to change the value change 23 to 2

2 answers

2


As you are working with ID selector, the code below is only 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>
  <input type="checkbox" id="checkbox" value="22">OIE
</label>

  • thank it worked but another question if I want to pass a string would look like this? $(this).val("Bom dia") ?

  • @Bryant That’s right.

  • intact in case I would have to use the this this was my mistake thank you!

1

Use $(this) to make things easier and exchange id for classes as a 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 functional example here.

If you use the Chrome debugger, you’ll see that the value has changed dynamically: inserir a descrição da imagem aqui

Browser other questions tagged

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