Angel
Angel

Reputation: 357

Apply css styles in table created in Javascript (JQuery Mobile)

I have a table that is created dynamically using PHP and Javascript. Now, I'm trying to styling the last one <tr> to add a padding and border, but it doesn't work.

How can I proceed? I need call some element like trigger('create') or others?

Part of my code:

$.ajax ( {
        beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
        complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
        url: "http://www.someweb.com/somePHP.php",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            for(var i = 0; i< data[1].length;i++){
                table += "<tr><td>"+data[1][i].mon_da+"</td>";
                table += "<td>"+Number(data[1][i].mon_qu).toFixed(2)+"€</td>";
                table += "<td>"+data[1][i].mon_con+"</td></tr>";
            }
            table += "<tr style='border:1px solid;padding-top:20px;'><td colspan='2'><b>Disp:</b></td><td><b>"+Number(data[0].usr_to).toFixed(2)+"€</b></td></tr>";
            document.getElementById("tableMo").innerHTML = table;
        }
    });

Upvotes: 2

Views: 851

Answers (4)

Jabran Saeed
Jabran Saeed

Reputation: 6168

You can do that using jquery css selector

Upvotes: 0

Phillip-juan
Phillip-juan

Reputation: 546

One way of doing this is to add a class to your tr tags like so:

table += "<tr class='rowStyle'><td>"+data[1][i].mon_da+"</td>";

now you can style the rows, or if you want to style the table itself, you can use jquery to get the parent of the row like so:

var obj = $('.rowStyle').closest('table');

and just give it an ID:

$(obj).attr('id','tableID');

Now just style it.

Although this is a lengthy method of doing it.

Hope this helps :)

Upvotes: 0

Fabiotocchi
Fabiotocchi

Reputation: 216

You can get the table element by id and then add CSS style property with javascript:

for example:

   document.getElementById("tableMo").style.border = "1px solid black";
document.getElementById("tableMo").style.padding = "10px";

Check out some DOM style tutorial, it might help you

http://www.w3schools.com/jsref/dom_obj_style.asp

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50229

You can't apply styles to <tr>s like that.

You can try applying them to the <td>s instead.

I would personally prefer to add a class to the tr and handle the styles externally to JS in a CSS file.

jsFiddle

HTML

<tr class="stylish">
    <td colspan='2'><b>Disp:</b></td>
    <td><b>"+Number(data[0].usr_to).toFixed(2)+"€</b></td>
</tr>

CSS

.stylish td {
    border:1px solid #000;
    padding-top:20px;
}
.stylish td:first-child {
    border-right:0;
}
.stylish td:last-child {
    border-left:0;
}

Upvotes: 3

Related Questions