javascript - 在 jquery 中将预填充表单制作为 HTML 表

标签 javascript jquery html

我正在尝试创建一个预填充表单,从 HTML 表中的任何选定行中提取值。 HTML 页面由 JSP 填充。

我的 table 看起来像这样

<table id="data-table" id="test">
    <thead>
        <tr>
            <th>value1</th>
            <th>value2</th>
            <th>value3</th>
            <th>value4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td id="class1"><%= value.valueOne() %></td>
            <td id="class2"><%= value.valueTwo() %></td>
            <td id="class3"><%= value.valueThree() %></td>
            <td id="class4"><%= value.valueFour() %></td>
        </tr>
        <%
        }
        %>
    </tbody>
</table>

我想获得一个预先填充的表单,其中包含单击特定行时的行值。我有一些 js 代码可以做到这一点。

$(document).on("click", ".data-table .class1", function(e) {
    var value =  $(this).closest('tr').val();
    console.log(value);
    // Just to check if I get the correct value 
});

不幸的是,我无法理解如何从 DOM 获取该特定行的值并将其填充到表单中,我想将其覆盖在表格上。我将不胜感激任何指点。我真的会写更多的代码,但我不知道 Jquery 并且被卡住了

最佳答案

您的总体策略应该是这样的:

  • 填充服务器端的表格:完成
  • 表单已存在于页面中,但用 css 隐藏 (display:none)
  • 在所有 tr 元素上注册点击监听器以:
    1. 查找 tr 中每个 td 内的值
    2. 选择相应的表单输入
    3. 使用 jQuery 的 val(value) 函数填充输入。
    4. 如果表单已隐藏,则取消隐藏该表单

考虑到这一点,我会将您的点击监听器从文档更改为类似这样的内容。 (注意:我假设 value.valueOne() 只是数字或字符串,并且不包含任何 html。

//target just TR elements
$('tr').click(function(){
  values = [];
  $(this).children().each(function(){
    //add contents to the value array.
    values.push($(this).html())
  });

  //fill in the form values
  populateForm(values);
});

填充表单完全取决于表单的 HTML,但为了帮助您开始,这里介绍了它的外观:

function populateForm(values){
  //set the value of the input with id of name to the value in the first td.
  $('#name').val(values[0]);
  //show the form (id inputForm) now that it's populated
  $('#inputForm').show();
}

关于javascript - 在 jquery 中将预填充表单制作为 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19799081/

相关文章:

javascript - jQuery 随机淡入图像

javascript - 隐藏(不是删除)Blueimp jquery fileupload 插件中的复选框

javascript - 如何打印特定 AJAX 函数中可用的 $_REQUEST?

html - 在第二列中移动 li 元素 - 仅限 CSS

javascript - 在 NW.js 中打开没有菜单栏的新窗口

javascript - 如何摆脱javascript中的instanceof

javascript - AJAX返回的数据不正确

javascript - 通过 jquery ajax 返回的我的 JSON 数据上的意外标记 u

javascript - 在 Chrome 和 IE 中记录元素的不同输出

html - 溢出时隐藏元素