最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Create row ID for dynamic JS Table - Stack Overflow

programmeradmin1浏览0评论

I have working script that the user pletes inputs on a form and when they submit the form and the content of the form inputs are entered as a table row.

Is there any way of, I think within the JS to make each row have a unique ID and add a delete button to the last colum of each row so the user can delete an individual row.

Thanks for saving a life!!!!

HTML Form

    <form id="my_form" action="table_form.php" method="post">
            <div style="width:10%; float:left;">
                Quantity<br />
                <input name="field_1" type="text" id="field_1" size="3" />
            </div>
            <div style="width:20%; float:left;">
                Part Number<br />
                <input type="text" id="field_2" name="field_2" />
            </div>
            <div style="width:30%; float:left;">
                Notes<br />
                <input name="field_3" type="text" id="field_3" size="45" />
            </div>
            <div style="width:20%; float:left;">
                Unit Price<br />
                <input type="text" id="field_4" name="field_4" />
            </div>
           <div style="width:20%; float:left;">
                <br />
                <input type="submit" value="Add Row" />
            </div>
        </form>

        <!-- 
            Here we create our HTML table.
            Note the ID of the table. This will be used in our javascript file
            Our table only contains a header row. All other content will be added dynamically
        --><? $rowid = 1; ?>
        <table width="100%" id="my_table">
        <tbody id="my_table_body">
         <tr>
          <th width="5%"><div align="left">Qty</div></th>
          <th width="19%"><div align="left">Part Number</div></th>
          <th width="46%"><div align="left">Notes</div></th>
          <th width="15%"><div align="left">Unit Price</div></th>
          <th width="15%"><div align="left">Row Total</div></th>
         </tr>
         </tbody>
</table>  


JS

window.addEvent('domready', function(){
    $('my_form').addEvent('submit', function(e){
            e.stop();
    this.set('send', {
                onComplete: function( response ){
    var data = JSON.decode(response);
    inject_row( $('my_table_body'), data );
                }
            });
    var valid_form = true;
            $$('#my_form input').each(function(item){
             if( item.value == '' ) valid_form = false;
            });
    if( valid_form ) {
                this.send();
            } else {
                alert('Fill in all fields');
            }

        });
    var inject_row = function( table_body, data ){
    var row_str = '<tr width="100%">';
            data.each( function(item, index){
                row_str += '<td>'+item+'</td>';
            });
            row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
    var newRow = htmlToElements( row_str );
    newRow.inject( table_body );

        }
    var htmlToElements = function(str){  
            return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');  
        }  

    });

PHP

<?php 

 /**
  * If nothing is being posted to this script redirect to
  * our HTML page.
  */
 if( ! $_POST ){
    header('Location: newquote.php');
 }

 // create an empty array for our results
 $results = array();

 /**
  * Stick the values from _POST into our results array
  * while also stripping out any html tags
  * 
  * This is where you would perform any required processing
  * of the form data such as server side validation or updating
  * a database.
  */
 foreach( $_POST as $field ){
    $results[] = strip_tags( $field );
 }

 // Echo our results as a JSON encoded string.
 echo json_encode( $results );

?>

I have working script that the user pletes inputs on a form and when they submit the form and the content of the form inputs are entered as a table row.

Is there any way of, I think within the JS to make each row have a unique ID and add a delete button to the last colum of each row so the user can delete an individual row.

Thanks for saving a life!!!!

HTML Form

    <form id="my_form" action="table_form.php" method="post">
            <div style="width:10%; float:left;">
                Quantity<br />
                <input name="field_1" type="text" id="field_1" size="3" />
            </div>
            <div style="width:20%; float:left;">
                Part Number<br />
                <input type="text" id="field_2" name="field_2" />
            </div>
            <div style="width:30%; float:left;">
                Notes<br />
                <input name="field_3" type="text" id="field_3" size="45" />
            </div>
            <div style="width:20%; float:left;">
                Unit Price<br />
                <input type="text" id="field_4" name="field_4" />
            </div>
           <div style="width:20%; float:left;">
                <br />
                <input type="submit" value="Add Row" />
            </div>
        </form>

        <!-- 
            Here we create our HTML table.
            Note the ID of the table. This will be used in our javascript file
            Our table only contains a header row. All other content will be added dynamically
        --><? $rowid = 1; ?>
        <table width="100%" id="my_table">
        <tbody id="my_table_body">
         <tr>
          <th width="5%"><div align="left">Qty</div></th>
          <th width="19%"><div align="left">Part Number</div></th>
          <th width="46%"><div align="left">Notes</div></th>
          <th width="15%"><div align="left">Unit Price</div></th>
          <th width="15%"><div align="left">Row Total</div></th>
         </tr>
         </tbody>
</table>  


JS

window.addEvent('domready', function(){
    $('my_form').addEvent('submit', function(e){
            e.stop();
    this.set('send', {
                onComplete: function( response ){
    var data = JSON.decode(response);
    inject_row( $('my_table_body'), data );
                }
            });
    var valid_form = true;
            $$('#my_form input').each(function(item){
             if( item.value == '' ) valid_form = false;
            });
    if( valid_form ) {
                this.send();
            } else {
                alert('Fill in all fields');
            }

        });
    var inject_row = function( table_body, data ){
    var row_str = '<tr width="100%">';
            data.each( function(item, index){
                row_str += '<td>'+item+'</td>';
            });
            row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
    var newRow = htmlToElements( row_str );
    newRow.inject( table_body );

        }
    var htmlToElements = function(str){  
            return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');  
        }  

    });

PHP

<?php 

 /**
  * If nothing is being posted to this script redirect to
  * our HTML page.
  */
 if( ! $_POST ){
    header('Location: newquote.php');
 }

 // create an empty array for our results
 $results = array();

 /**
  * Stick the values from _POST into our results array
  * while also stripping out any html tags
  * 
  * This is where you would perform any required processing
  * of the form data such as server side validation or updating
  * a database.
  */
 foreach( $_POST as $field ){
    $results[] = strip_tags( $field );
 }

 // Echo our results as a JSON encoded string.
 echo json_encode( $results );

?>
Share Improve this question edited Jul 28, 2009 at 18:22 asked Jul 28, 2009 at 15:55 BifterBifter 5
  • 1 "add a delete button to the last colum of each row so the user can delete an individual row" - Do you store the data server-side? Where does this delete operation take place? Server-side? Client-side? Both? – VolkerK Commented Jul 28, 2009 at 16:10
  • Nope nothing is stored SS - and the operation would take place CS. Adding a delete button is pretty straight forward it is giving the row a unique id so the user can only delete the corresponding row when the delete button is pressed. Thanks for looking. – Bifter Commented Jul 28, 2009 at 16:15
  • 1 Bifter, you don't need any IDs. When a button is pressed, simply traverse up the DOM to the nearest TR element and "delete" it... – James Commented Jul 28, 2009 at 17:28
  • Hi J-P thanks for answering, JS is notmy strong suit - could you possibly showme within my code above? – Bifter Commented Jul 28, 2009 at 17:35
  • just place a link like <a href="#" class="remove"> within a TD, then do $$("a.remove").addEvent("click", function(e) { new Event(e).stop(); this.getParent().dispose(); }); If within a div thats a child of a td, obviously do this.getParent().getParent().dispose(); to target the TR. – Dimitar Christoff Commented Jul 28, 2009 at 17:42
Add a ment  | 

3 Answers 3

Reset to default 2

I agree with J-P, it sounds like you don't need an unique id here.
Since the question is tagged "jquery" I suggest using the live event binding, e.g.

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready( function() {
        $(".deleterow").live("click", function() {
          $(this).parents("tr:first").remove();
        });
      });

      function foo(id) {
        $("#"+id).append('<tr><td>'+(new Date()).getSeconds()+'</td><td>x</td><button class="deleterow">delete</button></td></tr>');
      }
    </script>
  </head>
  <body>
    <table id="t1">
      <tr><td>a</td><td>A</td><td><button class="deleterow">delete</button></td></tr>
      <tr><td>b</td><td>B</td><td><button class="deleterow">delete</button></td></tr>
      <tr><td>c</td><td>C</td><td><button class="deleterow">delete</button></td></tr>
    </table>
    <button onclick="foo('t1')">add</button>
  </body>
</html>

The function passed to $(document).ready() is invoked when ...well, as the name states, when the document (dom) is ready.
$(".deleterow").live("click", ... : Whenever a click event occurs on an element with the css class "deleterow" the function passed as second parameter is invoked. In this case

function() {
  $(this).parents("tr:first").remove();
}

When the function is invoked the this-context is the element where the event occurred. parents("tr:first") returns the first/"nearest" tr element in the ancestor-axis of the current element. remove() is probably self-explaining...

edit: ok, now that the jquery tag is gone....
http://www.jaycarlson/blog/2009/04/06/live-events-in-mootools/ shows a live-event binding for mootools. Using that the "new" solution is quite similar to the jquery script

window.addEvent('domready', function() {
  // add an onclick handler for all current and future button elements
  // within the table id=t1
  $('t1').addLiveEvent('click', 'button', function(e){ 
    // a button in t1 has been clicked, this=button element
    // get the "nearest" tr in the parent/ancestor-axis
    // and remove it
    $(this).getParent("tr").dispose();
  });
});

This should be unique enough for this project:

var newDate = new Date;
var id = newDate.getTime();

Then it would just be a matter of adding it the row in your loop and linking it to your delete button.

I always use the php function uniqid(). It generates a unique id based on the time in microseconds. PHP Documentation.

You could loop through your results in PHP and add the result from uniqid() to each result before using json_encode().

发布评论

评论列表(0)

  1. 暂无评论