does not capture a class in ajax

Viewed 93

I'm having trouble changing a class with ajax, it works with the boton class but not with the boton_clic_sin class, please, someone who can help me. Thank you

$(document).ready(function() {
$('.btnguardar').on('click', function(e) {
    e.preventDefault();
    var $container = $(this).closest(".container");
    var id_oferta = $container.find(".id_oferta").val();
    var url_img = $container.find(".url_img").val();
    var $boton = $(this).closest('.boton');  
    var $boton_clic_sin = $(this).closest('.boton_clic_sin');

    $.ajax({
        type: "POST",
        url: "app/ofertasguardadasController.php",
        data: {
            id_oferta,  
            url_img},       
        success: function(r) {
            if (r==1) {         
            $('.aviso').empty();
            $('.aviso').append('Se agrego a la lista <a href="Las-Ofertas-que-mas-te-gustan"> Ver lista</a>').fadeIn("fast");
            $('.aviso').fadeOut(7000);
            $boton.addClass('deshabilita');
            $boton.attr('disabled', 'disabled');
            $boton_clic_sin.addClass('.habilita');
            $('.lista').html("Ver lista").fadeIn("slow");
            $('.title_lista').html("Agregado a la lista").fadeIn("slow");



            }

        }
    });
});                 

});

Html

<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>
2 Answers

If your span is located just before your button you can use prev() to get that element and use toggleClass to add or remove the added class.

Demo Code(I have removed some code which was not needed ) :

$('.btnguardar').on('click', function(e) {
  //find button prev element ->span
  var $boton_clic_sin = $(this).prev();
  //use toggle to add or remove class
  $boton_clic_sin.toggleClass('habilita');

});
.habilita {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>

You can change a class to your span element by using this $('.boton_clic_sin').addClass('habilita'); and $('.boton_clic_sin').removeClass('habilita'); Instead of doing this stuff var $boton_clic_sin = $(this).closest('.boton_clic_sin');, and a toggleClass

e.g.

$('.btnguardar').bind('click', function(e) {

    if($('.boton_clic_sin').hasClass('habilita')){
        $('.boton_clic_sin').removeClass('habilita');
    }else{
        $('.boton_clic_sin').addClass('habilita');
    }
    
});
.habilita{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="boton_clic_sin">♥</span>
<button id="btnguardar" class="boton btnguardar">♥</button>

Related