2011-09-02 62 views
0

我正在尋找一種方式通過jQuery/Javascript來填充一些輸入字段與數據我從表中獲取。我的表看起來像這樣:按下編輯按鈕時填充輸入字段

<tr> 
     <th>ticketID</th> 
      <th>eventID</th> 
      <th>name</th> 
      <th>price</th> 
      <th>priceWithinAllocation</th> 
      <th>&nbsp;</th> 
</tr> 
<tr > 
     <td class="ticketID">1</td> 
     <td class="eventID">1</td> 
     <td class="name">Sun</td> 
     <td class="price">300</td> 
     td class="priceWithinAllocation">150</td> 
     <td align="center"><input type="button" class="editRow" value="EDIT"/></td> 
</tr> 
<tr > 
     <td class="ticketID">2</td> 
     <td class="eventID">1</td> 
     <td class="name">Mon</td> 
     <td class="price">300</td> 
     <td class="priceWithinAllocation">150</td> 
     <td align="center"><input type="button" class="editRow" value="EDIT"/></td> 
</tr> 

我也有我想要的值出現在形式然而,並不是所有的值應該出現在那裏。

<p> 
<label for="">Name:</label> 
<input type="text" name="name" /> 

</p> 
<p> 
<label for="">Price:</label> 
<input type="text" name="price" /> 

</p> 
<p> 
<label for="">PriceWithinAllocation:</label> 
<input type="text" name="priceWithinAllocation" /> 

所以,說我點擊第一行的編輯按鈕,我想namepricepricewithinallocation出現在我的輸入字段。但是,我看不到這樣做。我嘗試了一些jQuery DOM遍歷,但那並沒有完全解決。任何人都可以在此看到任這甚至有可能嗎?

</p> 
<p> 
<input type="submit" id="saveNew" value="SAVE" /> 
<input type="button" id="cancelNew" value="CANCEL" />         

回答

2

試試這個:

$(function(){ 
    $(".editRow").click(function(){ 
     var name = $(this).parent().siblings(".name").text(); 
     var price = $(this).parent().siblings(".price").text(); 
     var priceWithinAllocation = $(this).parent().siblings(".priceWithinAllocation").text(); 
     $("[name='name']").val(name); 
     $("[name='price']").val(price); 
     $("[name='priceWithinAllocation']").val(priceWithinAllocation); 
    }); 
}); 

工作例如:http://jsfiddle.net/2QVQ6/

備選:

$(function(){ 
    $(".editRow").click(function(){ 
     $("[name='name']").val($(this).parent().siblings(".name").text()); 
     $("[name='price']").val($(this).parent().siblings(".price").text()); 
     $("[name='priceWithinAllocation']").val($(this).parent().siblings(".priceWithinAllocation").text()); 
    }); 
}) 
0

當然它的可能。

$('.editRow').click(function(){ 
    var $row = $(this).closest('tr'); 
    $('input[name="name"]').val($('.name',$row).text()); 
    $('input[name="price"]').val($('.price',$row).text()); 
    $('input[name="priceWithinAllocation"]').val($('.priceWithinAllocation',$row).text()); 
}) 

活生生的例子:http://jsfiddle.net/4tWjh/