I want to update an HTML class (without page refresh), the actual values are updating and the other items on the page are correct, but I can't update the background color of the class using the code I'm using.
I'm trying to get this:
<div class="col-md-3 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-green"><i class="alert_icon"></i></span> <div class="info-box-content"> <span class="info-box-text">Current Alarm State</span> <span class="info-box-number alerted"><small></small></span> </div> </div> </div>
Change to this (from bg-green to bg-red):
<div class="col-md-3 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="alert_icon"></i></span> <div class="info-box-content"> <span class="info-box-text">Current Alarm State</span> <span class="info-box-number alerted"><small></small></span> </div> </div> </div>
So my code looks like this:
<div class="col-md-3 col-sm-6 col-xs-12"> <div class="info-box"> <span class="alert_colour"><i class="alert_icon"></i></span> <div class="info-box-content"> <span class="info-box-text">Current Alarm State</span> <span class="info-box-number alerted"><small></small></span> </div> </div> </div>
JavaScript is like this:
$.ajax({ url: "update_all.php", type: "post", dataType: "json", success: function(response) { var len = response.length; for (var i = 0; i < len; i++) { var alert_colour = response[i].alert_colour; $(".alert_colour").attr('class', alert_colour); console.log(alert_colour); } }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); }, 1000);
The value of alert_colour when the page is loaded is info-box-icon bg-green
.
When the page loads, it works fine and shows the green box, but if the value of alert_colour
changes to info-box-icon bg-red
it doesn't update unless I refresh page.
In the console log output I see that it updates correctly (when the value changes from info-box-icon bg-green
to info-box-icon bg-red
, but on the screen it just stays as it was when the page loaded. There are other values (text) on the page that are being updated, just the class elements are not.
Since you appear to be changing the category of alert_status to alert_colour or something random like that, you lose your reference point for changing future categories.
For my answer, I actually referenced the alert_icon's parent, as that will allow you to reference it regardless of class.
Then as a test I added info-box-icon bg-red using addClass. Then I use removeClass without parameters and link it with addClass to add info-box-icon bg-green.
Also, since you are getting the classes from an array, you can pass them to jQuery's addClass function simply by concatenating the arrays with spaces.
Use attr and overwrite it every time.