Hermes Hermes - 1 year ago 150
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>

var lat = $('#lat').val();
var lng = $('#lng').val();
type: 'post',
url: 'kds_populate_db2.php?lat='+lat+'&lng='+lng,
data: {
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');


Answer Source

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';
<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download