dcsimg
www.webdeveloper.com
Results 1 to 3 of 3

Thread: For loop to create table not working

  1. #1
    Join Date
    Jan 2015
    Posts
    1

    For loop to create table not working

    for(var i=0; i<orderItemIndex; i++){
    document.writeln('<tr>');

    }
    document.writeln('<td>' + orderItemIndex[0] + '</td>');
    document.write('<td>' + productName[0] + '</td>');
    document.write('<td> $' + sausagePrice + '</td>');
    document.write('<td> ' + orderItemQty[0] + '</td>');
    document.write('<td> ' + sausageTotal + '</td>');
    document.writeln('</tr>');
    }

    orderItemIndex is an array with user inputs in it, I'm trying to make a new row for each individual array, the table is creating correctly but the loop is not working, if several inputs are added it just outputs the last input to one row, instead of making a new one each time, what am I missing? (The code above has other problems I know but I'm working on this first)

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,689
    Code:
    for(var i=0; i<orderItemIndex; i++){
     document.writeln('<tr>');
    
     }
     document.writeln('<td>' + orderItemIndex[0] + '</td>');
     document.write('<td>' + productName[0] + '</td>');
     document.write('<td> $' + sausagePrice + '</td>');
     document.write('<td> ' + orderItemQty[0] + '</td>');
     document.write('<td> ' + sausageTotal + '</td>');
     document.writeln('</tr>');
     }
    in your code the loop is in green

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,968
    The method of document.write is not a very good way to deal with this sort of output,
    Code:
    for(var i=0, str=''; i<orderItemIndex; i++){
        str += '<tr>';
        str += '<td>' + orderItemIndex[0] + '</td>';
        str += '<td>' + productName[0] + '</td>';
        str += '<td> $' + sausagePrice + '</td>';
        str += '<td> ' + orderItemQty[0] + '</td>';
        str += '<td> ' + sausageTotal + '</td>';
        str += '</tr>';
    }
    // then populate the DOM with the resulting string, 
    // document.write methods out of date
    STOP using $ prefix on JavaScript variable names...
    Please remember to wrap any code you have in forum tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles