Hermes Hermes - 2 months ago 18
jQuery Question

Change button class on success ajax result

I use Bootstrap a button and span. When the button is clicked I call an ajax function if result is success I want to change button class, button text and span class. The classes is changing but not working correctly. When the class is changed the button size is increasing.

<button id="check" type="" class="btn btn-danger btn-block"><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span> Check</button>

$("#check").click(function(){
var lat = $('#lat').val();
var lng = $('#lng').val();
$.ajax({
type: 'post',
url: 'kds_populate_db2.php?lat='+lat+'&lng='+lng,
data: {
lat:lat,
lng:lng
},
async: true,
cache: false,
success: function(data) {
$("#check").addClass('btn btn-success btn-block').removeClass('btn btn-danger btn-block');
$('#check>span').removeClass('glyphicon glyphicon-remove').addClass('glyphicon glyphicon-ok');
$("#check").val("checked");

}
});
});

Answer

Your problem is in this line:

$("#check").addClass('btn btn-success btn-block').removeClass('btn btn-danger btn-block');

invert remove and add class:

$("#check").removeClass('btn btn-danger btn-block').addClass('btn btn-success btn-block');

The snippet:

$(function () {
  $('#chengeIt').on('click', function(e) {
    $("#check").removeClass('btn btn-danger btn-block').addClass('btn btn-success btn-block')[0].childNodes[1].textContent = 'Success';
    $('#check>span').removeClass('glyphicon-check').addClass('glyphicon-ok-sign');
    $("#check").val("checked");
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<button id="check" type="" class="btn btn-danger btn-block"><span class="glyphicon glyphicon glyphicon-check" aria-hidden="true"></span> Check</button>
<button id="chengeIt" type="button" class="btn btn-primary">Check</button>

Comments