Get the values of 2 HTML input tags having the same name using PHP

后端 未结 4 1660
旧时难觅i
旧时难觅i 2021-01-21 00:41

Suppose I have the following table:

相关标签:
4条回答
  • 2021-01-21 00:51

    Quick solution:

    It is not complicated to change the input tags names in that code you have. Just try this:

    <input type="text" name="id"'+counter+' size="2" value="'+counter+'"/>
    

    That way, you will get names like id-1, id-2, id-3...

    0 讨论(0)
  • 2021-01-21 01:07

    When you have repeated names, you have to give them array-style names:

    <form  action="bla.php" method=post>
    <table class="pv-data">
    <tr>
    <td><input type="text" name="id[]" size="2" value=1 /></td>
    <td><input type="text" name="longitude[]" size="7"/></td>
    <td><input type="text" name="latitude[]" size="7"/></td>
    </tr>
    <tr>
    <td><input type="text" name="id[]" size="2" value=2 /></td>
    <td><input type="text" name="longitude[]" size="7"/></td>
    <td><input type="text" name="latitude[]" size="7"/></td>
    </tr>
    </table>
    <input type="submit" name="submit" value="SUBMIT">
    </form>
    

    When you do this, $_POST['id'], $_POST['latitude'], and $_POST['longitude'] will be arrays containing the values.

    Your form processing code can then iterate over these:

    for ($i = 0; $i < count($_POST['id']); $i++) {
      if (isset($_POST['latitude'][$i], $_POST['longitude'][$i])) { // Make sure both are filled in
        // Do stuff with this row of the form
      }
    }
    
    0 讨论(0)
  • 2021-01-21 01:12

    Well, I understand that there are dynamic rows generating. But it doesn't mean that you can't give the text boxes in each rows different names. You can definitely make it different. I saw your code in jsfiddle. While appending, you just count number of rows in the table and accordingly you, you can +1 to that and store it in a variable. And concatenate this variable in the name of the text box. So, that everytime, it will click add unit, text box in the row will have different name. Thats the correct solution.

    0 讨论(0)
  • 2021-01-21 01:14

    When PHP populates $_POST, if multiple pieces of data have the same name, and that name does not end in [] then only one will survive to appear in the $_POST array.

    Rename the fields so the names ends in [].

    don't tell me to change the name of the input tags, because the table is bit more complicated than that and it has dynamic add rows

    Being dynamic shouldn't be a barrier to having [] on the end of the name.

    If you really can't change the name then it might be possible to bypass $_POST entirely and parse the raw data (via php://input) but IIRC, PHP clobbers that when it populates $_POST.

    0 讨论(0)
提交回复
热议问题