Exchange on click for checkox checked

Asked

Viewed 85 times

0

Hello, I have a function that works perfectly in javascript use an ajax when clicking the button to send my data, only now instead of clicking the button, I want to change for when the person marks the checkbox, he should perform the function in the same way, It just doesn’t work at all. If you can help me thank you. I tried to do so:

var addProduto = function(){

      //termos é o nome do meu checkbox
      if (document.getElementById('termos').checked) {

           var id_produto = $(this).attr('data-id');

            $.ajax({
               type: 'post',
               url: url_painel +'carrinho/add',
               data: {id:id_produto},
               dataType: "JSON"
            }).then(function(res){

               if (res.erro == 0) {

                 alert ('produto adicionado com sucesso');

               } else{

                 alert(res.msg);

               }

            }, function(){
                alert('Erro');
            });             
            } else{
                alert('Você precisa aceitar os termos e uso de serviços antes de continuar');
            }


    }

It works with :

$('.btn-add-produto-carrinho').on('click', function(){

But not with checkbox. If you can help me thank.

2 answers

3

Hello, you could add the click event to the field checkbox to trigger the function with ajax.

Example:

const checkboxTermos = document.querySelector("#termos");
checkboxTermos.onclick = function() {
  //verifica se o campo checkbox está marcado
  if (this.checked) {
    console.log("true");
  } else {
    console.log("false");
  }
};
<div>
  <input type="checkbox" id="termos">
  <label for="termos">termos</label>
</div>

  • Vlw by help tb friends.

3


Good Morning!!

Javascript is listening to events, IE, your checkbox is not working because when you start your page, it already initializes this JS, probably appearing the message of the condition Else.

You can do like Francisco segeriu by adding the onclick event to your input:checkbox tag, or by using addeventlistener, as in the example below.

let checkboxTermos = document.querySelector("#termos");

checkboxTermos.addEventListener( 'change', function() {
    if(this.checked) {
        console.log("Executa o código quando a Checkbox estiver ticada")
    } else {
        console.log("Executa quando não estiver ticada")
    }
});
<label>Li e concordo com os termpos</label>
<input id="termos" type="checkbox">

  • mto thanks for the help, I did just as demonstrated only that then it nullifies my ajax, falls right into the error. And on the button it sends the normal data, only with the checkbox it overrides the ajax function.

  • What do you mean? You only call this evendo when you click the checkbox. Since you are using Jquery in your Ajax, why not use it to do the function? $(Function() { $('#terms'). change(Function(e) { e.preventDefault(); $.ajax({ url: "", type: 'post', Success: Function(result) { }, error: Function() { } }); }); });

  • I made a change in ajax and got it with your help. Vlw friend.

Browser other questions tagged

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