Using text values of span as numeric values

I am reading the innerHtml of two span’s and each are numeric values, for instance a 6 and 14.

I can store them in var’s and detect them, but what I need to try and do is read them as numeric values to use in the if statement, but its not working.

    function countingRecords() {

        var recordsShown = $("#RecordsShown").text();
        var recordsTotal = $("#TotalNumberOfRecords").text();

        alert(recordsShown + recordsTotal);
// this alert shows 614, the 6 is one and 14 the other

        if (recordsShown < recordsTotal) {
            alert("test");
        }
    }

While the comparison also works with string numbers, the + operator has three different meanings, depending on the expression:

  • if either operand is a string => string concatenation
  • if both operands are numbers => addition
  • if it’s used as a ‘prefix’ (i.e. (+b)) => type conversion to a number

The first alert is just for my benefit really, its the if statement I’m stuck with, its not recognising when the one value is less than the other value in a numeric sense.

Tried this too and again its not working

if ($(recordsShown).val() < $(recordsTotal).val()) {
   $("#TotalNumberOfRecords").after("<span class='returnRecordsToAll'>clear</span>");
   //alert("test");
}

Tried this too and get NaN as the alert

        var recordsShown = parseInt('#RecordsShown');
        var recordsTotal = parseInt('#TotalNumberOfRecords');

        alert(recordsShown + recordsTotal);

Ok looks like Ive got it

        var recordsShown = parseInt($('#RecordsShown').text(), 10);
        var recordsTotal = parseInt($('#TotalNumberOfRecords').text(), 10);

        if (recordsShown < recordsTotal) {
            $("#TotalNumberOfRecords").after(" | <span class='returnRecordsToAll'>clear</span>");
        }

As previously mentioned, that would have worked even without parseInt().

As previously mentioned, that would have worked even without parseInt().

Yeah, but leaning on type coercion isn’t good practice.

Especially when it’s incorrect.

Javascript does NOT do implicit type conversion for number string comparitors if it can help it - If passed two number strings as operands of a comparitor, it will do a STRING comparisson between the two - thus, “120” < “20” is TRUE.

1 Like

Yeah, it was my understanding that “1” == 1 will return true, but “1” === 1 will not return true because of type.

V/r,

^ _ ^

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.