简体   繁体   中英

Using javascript so that the numerics are right aligned and others are left aligned

I have used this javascript function:

$(document).ready(function(){
    $("td").each(function() {
       if (parseInt($(this).text()) > 0) {
            $(this).css("text-align", "right");
        }
    });
});

By this all the numbers are right aligned. But I want that the string entered should be left aligned. I think that by using NaN it is possible but I don't know how to use it. Can some one tell me the way to use NaN or some other function?

You can do something like this:

$(document).ready(function(){
    $("td").each(function() {
       var item = $(this);
       if (item.text().match(/^-?\d+$/)) {
            item.css("text-align", "right");
        } else {
            item.css("text-align", "left");
        }
    });
});

Working example: http://jsfiddle.net/jfriend00/MyqrG/

Why can't you use the typeof operator to determine between number and string.

$( document ).ready( function() {
    $( "td" ).each( function() {
       var textVal = $( this ).text();
       var type = !isNaN(parseFloat(textVal)) && isFinite(textVal);

       if ( !type ) {
            $( this ).css( "text-align", "left" );
       } else if ( type ) {
            $( this ).css( "text-align", "right" );
       }
    });
});

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM