Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write to a span using jQuery?

I'm trying to populate a <span></span> element on the page load with jQuery.

At the moment the value that gets 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();
    });
});
like image 315
Pomster Avatar asked Dec 01 '22 05:12

Pomster


1 Answers

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);
    });
like image 197
Denys Séguret Avatar answered Dec 04 '22 09:12

Denys Séguret