使用Jquery在表中显示表单

时间:2013-02-19 18:28:27

标签: jquery html ajax html-table

我有一张包含各种行的表格。每行包含项目描述和订购项目的链接。我现在需要在点击链接时在该行下方显示一个表单。

我可以通过为每个表行使用多个表单并使用Jquery hide()show()函数来完成它。但这似乎不合逻辑。

有没有更好的方法。就像我只能在一个地方创建表单,并在单击链接时调用它,它显示在表格行的下方。

<table>
<tr>
  <td> The Item Description </td>
  <td><a href=""> Order now </td>
</tr>
<tr>
  <!-- the form should be here , it should be initially hidden but must be displayed when the link is clicked. I will have a huge number of Items -->
</tr>
</table>

3 个答案:

答案 0 :(得分:3)

您可以创建一个填充表单的函数,是的。

function populate(description, quantity) {
  $('#myForm').show();
  $('#description', '#myForm').val(description);
  $('#quantity', '#myForm').val(quantity);
}

并且您应该将该函数绑定到onclick事件

$('a.order').click(function(){
  var desc = $('.description', $(this)).text(),
      quan = $('.quantity', $(this)).text();
  populate(desc,quan);
  $('#myForm').insertAfter($(this).parent()); // to 'move' the form after the <td> parent of <a>
  return false;
});

答案 1 :(得分:2)

我的版本。我将表单隐藏起来,然后将其附加到临时行:

var $form  = $('.form'),
    $table = $('.table');

$table.on('click', '.link', function(e) {
    e.preventDefault();
    $table.find('tr.temp-row').remove();
    $(this).closest('tr').after(function() {
        var $tr = $('<tr class="temp-row"><td colspan="4"></td></tr>');
        return $tr.find('td').html($form).end();
    });
});

http://jsfiddle.net/3XWUz/

答案 2 :(得分:0)

您可以为每个订单按钮添加一个类,然后在点击其中一个按钮时切换为tr

<table>
<tr>
  <td> The Item Description </td>
  <td><a href="" class="order"> Order now </td>
</tr>
<tr>
  <td> The Item Description </td>
  <td><a href="" class="order"> Order now </td>
</tr>
<tr>
  <td> The Item Description </td>
  <td><a href="" class="order"> Order now </td>
</tr>
<tr>
  <td> The Item Description </td>
  <td><a href="" class="order"> Order now </td>
</tr>
<tr id="form_tr" style="display: none;">
  <td colspan="2">
  <!-- the form should be here , it should be initially hidden but must be displayed when the link is clicked. I will have a huge number of Items -->
  </td>
</tr>
</table>

jQuery的:

$('.order').click(function() {
  $('#form_tr').toggle();
    return false;
});

您需要添加更多代码才能使用正确的产品更新表单,但这是一般的想法。