Pomster Pomster - 7 months ago 5
Javascript Question

How do you write to a span using jquery?

Hi i'm trying to populate a span on the page load with jquery.

At the moment the value populated into the span is just an integer count.

Here i have named my span userCount:

<a href="#" class="">Users<span id = "userCount"></span></a>


I am trying to write the value of the span with no success.

$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {

var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;

var countUsers

for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();

});

});

Answer

You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.

 $('#userCount').html(countUsers);

Note also that

  • you don't need to convert your integer to a string manually.
  • if you don't break from the loop, countUsers will always be table.length-1.
  • you have a typo : dataSet instead of dataset. Javascript is case sensitive.
  • you don't need to parse the result of the request
  • you don't need to pass empty data : jQuery.post checks the type of the provided parameters

So, this is probably more what you need, supposing you do other things in the loop :

    $.post("Dashboard/UsersGet", function (dataset) {
        var table = dataset.Table;
        var countUsers = table.length; // -1 ?
        // for now, the following loop is useless
        for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
            var array = table[i];
            if (array.Active == 1) { // I hope array isn't an array...
                var name = array.Name; // why ? This serves to nothing
            }
        }
        $('#userCount').html(countUsers);
    });
Comments