代码之家  ›  专栏  ›  技术社区  ›  Henry Sachs

获取表内多个输入的值[闭合]

  •  -8
  • Henry Sachs  · 技术社区  · 7 年前

    嘿,伙计们,我有一张桌子,看起来像这样:

    <table>
      <tr>
        <td></td>
        <td></td>
        <td>
          <input type="text" name="test1" placeholder="Test1">
          <input type="text" name="test2" placeholder="Test2">
          <input type="text" name="test3" placeholder="Test3">
          <input type="text" name="test4" placeholder="Test4"></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td>
          <input type="text" name="test1" placeholder="Test4">
          <input type="text" name="test2" placeholder="Test5">
          <input type="text" name="test3" placeholder="Test6">
        </td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td>
          <input type="text" name="test1" placeholder="Test7">
          <input type="text" name="test2" placeholder="Test8">
        </td>
      </tr>
    
    </table>

    td 对于每个表行。如果我能将每个值存储在一个字符串中,并用“;”分隔这些值,那么我会做得更好然后将这个字符串存储在一个数组中。所以在这个特定的例子中,有3个带值的字符串。我使用JavaScript和Jquery,非常感谢您的帮助。

    所以是的,我已经尝试对每个tr使用foreach条件,但没有成功。

    我的JS代码如下所示:

    $(document).ready(function() {
      var valueArray[];
      $("button").click(function(event) {
       $("tr").each(function(index) {
         var valueString;
       $("td input").each(function(){
         valueString += this.value;
        });
      valueArray.push(valueString);
      });
     });
    });
    

    上次编辑:

    伙计们,多亏了阿伦,我现在有了一个解决方案,我只需要做一些配置:

    $(document).ready(function() {
      var ressultArray = [];
      $("button").click(function(event) {
        var trResult = '';
        $('table').find('tr').each(function() {
          $(this).find('td input').each(function() {
            if (trResult.indexOf($(this).val()) === -1)
              trResult += $(this).val() + ';';
          });
          var result = trResult.slice(0, -1);
          console.log(result);
          console.log(trResult);
          ressultArray.push(result);
          trResult = '';
        });
        console.log(ressultArray);
      });
    });
    

    这里有一个要测试的plunker: https://plnkr.co/edit/GMOgDA9dB0Y5Eosu0hVR?p=preview

    1 回复  |  直到 7 年前
        1
  •  0
  •   Alen.Toma    7 年前

    你可以把每一个td循环扔成一行。

    $('table').find('tr').each(funtion(){
    var trResult= '';
    $(this).find('td').each(function()
    {
    IF(trResult.indexOf($(this).val()) ===-1)
    trResult += $(this).val() +';';
    });
    });
    

    这是我手机上写的,很抱歉格式化不好