1

ユーザーがフォームへの入力を完了し、フォームを送信するとフォーム入力の内容がテーブル行として入力される作業スクリプトがあります。

JS内で各行に一意のIDを持たせ、各行の最後の列に削除ボタンを追加して、ユーザーが個々の行を削除できるようにする方法はありますか?

命を救ってくれてありがとう!!!!

HTMLフォーム

    <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 );

?>
4

3 に答える 3

2

JPに同意します。ここでは一意のIDは必要ないようです。
質問には「jquery」というタグが付けられているので、live event bindingを使用することをお勧めします。

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/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>

$(document).ready() に渡された関数は、名前が示すように、ドキュメント (dom) の準備が整ったときに呼び出されます。
$(".deleterow").live("click", ... : css クラス "deleterow" を持つ要素でクリック イベントが発生するたびに、2 番目のパラメーターとして渡された関数が呼び出されます。この場合、

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

関数が呼び出されると、this-context はイベントが発生した要素です。parent("tr:first") は、現在の要素の祖先軸にある最初の/「最も近い」tr 要素を返します。remove() はおそらく自明です...

編集: jquery タグがなくなったので....
http://www.jaycarlson.net/blog/2009/04/06/live-events-in-mootools/は、mootools のライブ イベント バインディングを示しています。それを使用すると、「新しい」ソリューションはjqueryスクリプトに非常に似ています

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();
  });
});
于 2009-07-28T17:39:07.433 に答える
1

私は常に php 関数を使用しますuniqid()。マイクロ秒単位の時間に基づいて一意の ID を生成します。 PHP ドキュメント

を使用する前に、PHP で結果をループし、uniqid()各結果にからの結果を追加できますjson_encode()

于 2009-07-28T16:59:45.343 に答える
1

これは、このプロジェクトに対して十分に一意である必要があります。

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

次に、ループの行に追加して、削除ボタンにリンクするだけです。

于 2009-07-28T16:38:23.500 に答える