4 สิงหาคม 2553

Jquery เพิ่มแถวใหม่

ส่วน โค้ด ของ Jquery
**************************************************************************
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
        var id = document.getElementById("id").value;       
    $('#add-row').click(function(){
       
        var str = "";
        $("#select option:selected").each(function () {
            str = $(this).text();
            //alert(str);
        });
        var tr = $('<tr width="343" id="row'+id+'">#</tr>');
        var td1 = $('<td width="83"><input type="hidden" name="branch_id[]" id="branch_id[]" value="'+$('#select').val() +'"/></td>');
        var td2 = $('<td width="253">'+str+'</td>');
        var td3 = $('<td><a href="#" onClick="removeFormField(\'#row'+id+'\'); return false;">Remove</a></td>');
       
        tr.append(td1);
        tr.append(td2);
        tr.append(td3);

        $('#tbl-product').append(tr);
        id = (id - 1) + 2;
        document.getElementById("id").value = id;

    });
   
    $("#delete-row").click(function(){
        if($("#tbl-product tr").size()>1){
            $("#tbl-product tr:last").remove();
        }else{
            alert("Have Mor 1 !");
        }
    });   
   
})

function removeFormField(id) {
    $(id).remove();
}
   
</script>

**************************************************************************
ส่วนที่ทดลองใช้งาน

<?php if(empty($_POST)){ ?>
<input type="hidden" id="id" value="1">
<form id="form1" name="form1" method="post" action="">
  <table width="348" id="tbl-product">
    <tr id="firstTr">
      <th width="83">ID</th>
      <th width="253">product</th>
      <th width="253"> </th>
    </tr>
  </table>
  <table width="348" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="68"><input type="button" name="add-row" id="add-row" value="ADD" /></td>
      <td width="69"><input type="button" name="delete-row" id="delete-row" value="DELETE" /></td>
      <td width="211">
          <select name="select" id="select">
            <option value="1">test 1</option>
            <option value="2">test 2 </option>
            <option value="3">test 3 </option>
            <option value="4">test 4</option>
            <option value="5">test 5</option>
           
          </select>
      </td>
    </tr>
  </table>
  <input type="submit" name="button" id="button" value="Submit" />
</form>

<?php } else { ?>

    <?php
        print_r($_POST['branch_id']);
    ?>

<?php } ?>