58

I'm trying to create a table where each row is a form. I want that each input is in a different table division, but I still need that for example, all first inputs belong to the same table head and so on.

What I'm trying to do is an editable grid, more or less this:

<table>
    <tr>
        <form method="POST" action="whatever">
            <td><input type="text"/></td>
            <td><input type="text"/></td>
        </form>
    </tr>
    <tr>
        <form method="POST" action="whatever">
            <td><input type="text"/></td>
            <td><input type="text"/></td>
        </form>
    </tr>
</table>

But apparently I cannot arrange the tags in that way (or so is what the w3c validator said).

Any good way to do this?

Martlark
  • 12,242
  • 12
  • 73
  • 89
vtortola
  • 32,045
  • 25
  • 144
  • 246
  • 3
    http://www.hotdesign.com/seybold/ – Stephen Oct 27 '10 at 17:37
  • why not get rid of the forms and ajaxified your table. – Funky Dude Oct 27 '10 at 17:45
  • 2
    As been discussed in the answers it seems that a better alternative is to use some sort of AJAX to do this. The following question contains a collection of jQuery grid plugins that will enable you to do what you want; hopefully you find this helpful. http://stackoverflow.com/questions/159025/jquery-grid-recommendations – Waleed Al-Balooshi Oct 27 '10 at 17:54
  • A similar question http://stackoverflow.com/questions/5967564/form-inside-a-table which has good answers. – Sanghyun Lee Jun 22 '16 at 05:08

12 Answers12

100

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

Matthew
  • 7,255
  • 10
  • 33
  • 63
13

If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET to POST (unless you know that you're not going to be sending more than the max amount of data a GET request can send).

(That's assuming, of course, that all of the data is going to the same place.)

<form method="POST" action="your_action">
<table>
<tr>
<td><input type="text" name="r1c1" value="" /></td>
<!-- ... snip ... -->
</tr>
<!-- ... repeat as needed ... -->
</table>
</form>
Sean Vieira
  • 140,251
  • 31
  • 286
  • 277
  • 1
    This is probably the best solution. – Stephen Oct 27 '10 at 17:53
  • 1
    If I understand you correctly, you're trying to make a datagrid, both to display existing data, and to enable editing / data entry. The best bet would be to use javascript to create and build this datagrid -- there are *many* good ones out there. – Sean Vieira Oct 27 '10 at 17:54
10

If using JavaScript is an option and you want to avoid nesting tables, include jQuery and try the following method.

First, you'll have to give each row a unique id like so:

<table>
  <tr id="idrow1"><td> ADD AS MANY COLUMNS AS YOU LIKE  </td><td><button onclick="submitRowAsForm('idrow1')">SUBMIT ROW1</button></td></tr>
  <tr id="idrow2"><td> PUT INPUT FIELDS IN THE COLUMNS  </td><td><button onclick="submitRowAsForm('idrow2')">SUBMIT ROW2</button></td></tr>
  <tr id="idrow3"><td>ADD MORE THAN ONE INPUT PER COLUMN</td><td><button onclick="submitRowAsForm('idrow3')">SUBMIT ROW3</button></td></tr>
</table>

Then, include the following function in your JavaScript for your page.

<script>
function submitRowAsForm(idRow) {
  form = document.createElement("form"); // CREATE A NEW FORM TO DUMP ELEMENTS INTO FOR SUBMISSION
  form.method = "post"; // CHOOSE FORM SUBMISSION METHOD, "GET" OR "POST"
  form.action = ""; // TELL THE FORM WHAT PAGE TO SUBMIT TO
  $("#"+idRow+" td").children().each(function() { // GRAB ALL CHILD ELEMENTS OF <TD>'S IN THE ROW IDENTIFIED BY idRow, CLONE THEM, AND DUMP THEM IN OUR FORM
        if(this.type.substring(0,6) == "select") { // JQUERY DOESN'T CLONE <SELECT> ELEMENTS PROPERLY, SO HANDLE THAT
            input = document.createElement("input"); // CREATE AN ELEMENT TO COPY VALUES TO
            input.type = "hidden";
            input.name = this.name; // GIVE ELEMENT SAME NAME AS THE <SELECT>
            input.value = this.value; // ASSIGN THE VALUE FROM THE <SELECT>
            form.appendChild(input);
        } else { // IF IT'S NOT A SELECT ELEMENT, JUST CLONE IT.
            $(this).clone().appendTo(form);
        }

    });
  form.submit(); // NOW SUBMIT THE FORM THAT WE'VE JUST CREATED AND POPULATED
}
</script>

So what have we done here? We've given each row a unique id and included an element in the row that can trigger the submission of that row's unique identifier. When the submission element is activated, a new form is dynamically created and set up. Then using jQuery, we clone all of the elements contained in <td>'s of the row that we were passed and append the clones to our dynamically created form. Finally, we submit said form.

Nisse Engström
  • 4,555
  • 22
  • 24
  • 38
b_laoshi
  • 355
  • 5
  • 11
  • I tried this approach but I am using ajax requests so now all these rows are getting appended at the bottom of my table. Trying to figure out a way of hiding these. – rii Oct 21 '15 at 19:25
  • Good suggestion! For this code to work in FireFox I had to add `form.style.display = "none"; document.body.appendChild(form);` just before the form.submit(); And make sure to use the same var idRow instead of id. – ISQ Jun 05 '16 at 17:42
  • Awesome answer. Saved me days. – Abhijeet Nagre Feb 04 '17 at 12:05
10

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Eli
  • 88,788
  • 20
  • 72
  • 81
  • 15
    certainly answers the question - but damn that's ugly :) – Prescott Oct 27 '10 at 17:41
  • 7
    Yes, this question is probably a symptom of doing something the wrong way, but it seems like we should answer the question in addition to ragging on it. – Eli Oct 27 '10 at 17:45
  • 2
    -1 for showing someone how to do something *even more* incorrectly. – Stephen Oct 27 '10 at 17:51
  • 7
    Actually, this one is valid markup, much as I wouldn't use it. – Eli Oct 28 '10 at 00:12
  • Valid, but probably not acceptable for most cases. When you wrap it like this, all your columns lose their alignment. –  Jan 14 '16 at 16:12
  • This is the thing no one should ever do... (referring to html markup not jquery serialization) – Alessio May 03 '19 at 13:11
4

If all of these rows are related and you need to alter the tabular data ... why not just wrap the entire table in a form, and change GET to POST (unless you know that you're not going to be sending more than the max amount of data a GET request can send).

I cannot wrap the entire table in a form, because some input fields of each row are input type="file" and files may be large. When the user submits the form, I want to POST only fields of current row, not all fields of the all rows which may have unneeded huge files, causing form to submit very slowly.

So, I tried incorrect nesting: tr/form and form/tr. However, it works only when one does not try to add new inputs dynamically into the form. Dynamically added inputs will not belong to incorrectly nested form, thus won't get submitted. (valid form/table dynamically inputs are submitted just fine).

Nesting div[display:table]/form/div[display:table-row]/div[display:table-cell] produced non-uniform widths of grid columns. I managed to get uniform layout when I replaced div[display:table-row] to form[display:table-row] :

div.grid {
    display: table;
}

div.grid > form {
    display: table-row;


div.grid > form > div {
    display: table-cell;
}
div.grid > form > div.head {
    text-align: center;
    font-weight: 800;
}

For the layout to be displayed correctly in IE8:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, IE=10" />

Sample of output:

<div class="grid" id="htmlrow_grid_item">
<form>
    <div class="head">Title</div>
    <div class="head">Price</div>
    <div class="head">Description</div>
    <div class="head">Images</div>
    <div class="head">Stock left</div>
    <div class="head">Action</div>
</form>
<form action="/index.php" enctype="multipart/form-data" method="post">
    <div title="Title"><input required="required" class="input_varchar" name="add_title" type="text" value="" /></div>

It would be much harder to make this code work in IE6/7, however.

Dmitriy Sintsov
  • 2,949
  • 25
  • 17
3

If you can use javascript and strictly require it on your web, you can put textboxes, checkboxes and whatever on each row of your table and at the end of each row place button (or link of class rowSubmit) "save". Without any FORM tag. Form than will be simulated by JS and Ajax like this:

<script type="text/javascript">
$(document).ready(function(){
  $(".rowSubmit").click(function()
  {
     var form = '<form><table><tr>' + $(this).closest('tr').html() + '</tr></table></form>';
     var serialized = $(form).serialize(); 
     $.get('url2action', serialized, function(data){
       // ... can be empty
     }); 
   });
});        
</script>

What do you think?

PS: If you write in jQuery this:

$("valid HTML string")
$(variableWithValidHtmlString)

It will be turned into jQuery object and you can work with it as you are used to in jQuery.

Racky
  • 1,103
  • 16
  • 23
  • PS: If rows are added dynamically by javascript, event "click" won't work if defined as shown. In that case define the event by jQuery.live() or jQuery.on() – Racky Mar 06 '13 at 07:08
2

If you need form inside tr and inputs in every td, you can add form in td tag, and add attribute 'form' that contains id of form tag to outside inputs. Something like this:

<tr>
  <td>
    <form id='f1'>
      <input type="text">
    </form>
  </td>
  <td>
    <input form='f1' type="text">
  </td>
</tr>
Ray
  • 3,693
  • 7
  • 24
  • 33
2

You can use the form attribute id to span a form over multiple elements each using the form attribute with the name of the form as follows:

<table>
     <tr>
          <td>
               <form method="POST" id="form-1" action="/submit/form-1"></form>
               <input name="a" form="form-1">
          </td>
          <td><input name="b" form="form-1"></td>
          <td><input name="c" form="form-1"></td>
          <td><input type="submit" form="form-1"></td>
     </tr>
</table>
Martlark
  • 12,242
  • 12
  • 73
  • 89
  • Getting Error - "Can't bind to 'form' since it isn't a known property of 'input'. " – Bhupendra Kumar Sep 09 '20 at 18:56
  • @BhupendraKumar What system are you using that throws this error? Sounds like your development environment is ignorant of the more esoteric properties. – Martlark Dec 15 '20 at 03:58
1

I had a problem similar to the one posed in the original question. I was intrigued by the divs styled as table elements (didn't know you could do that!) and gave it a run. However, my solution was to keep my tables wrapped in tags, but rename each input and select option to become the keys of array, which I'm now parsing to get each element in the selected row.

Here's a single row from the table. Note that key [4] is the rendered ID of the row in the database from which this table row was retrieved:

<table>
  <tr>
    <td>DisabilityCategory</td>
    <td><input type="text" name="FormElem[4][ElemLabel]" value="Disabilities"></td>
    <td><select name="FormElem[4][Category]">
        <option value="1">General</option>
        <option value="3">Disability</option>
        <option value="4">Injury</option>
        <option value="2"selected>School</option>
        <option value="5">Veteran</option>
        <option value="10">Medical</option>
        <option value="9">Supports</option>
        <option value="7">Residential</option>
        <option value="8">Guardian</option>
        <option value="6">Criminal</option>
        <option value="11">Contacts</option>
      </select></td>
    <td>4</td>
    <td style="text-align:center;"><input type="text" name="FormElem[4][ElemSeq]" value="0" style="width:2.5em; text-align:center;"></td>
    <td>'ccpPartic'</td>
    <td><input type="text" name="FormElem[4][ElemType]" value="checkbox"></td>
    <td><input type="checkbox" name="FormElem[4][ElemRequired]"></td>
    <td><input type="text" name="FormElem[4][ElemLabelPrefix]" value=""></td>
    <td><input type="text" name="FormElem[4][ElemLabelPostfix]" value=""></td>
    <td><input type="text" name="FormElem[4][ElemLabelPosition]" value="before"></td>
    <td><input type="submit" name="submit[4]" value="Commit Changes"></td>
  </tr>
</table>

Then, in PHP, I'm using the following method to store in an array ($SelectedElem) each of the elements in the row corresponding to the submit button. I'm using print_r() just to illustrate:

$SelectedElem = implode(",", array_keys($_POST['submit']));
print_r ($_POST['FormElem'][$SelectedElem]);

Perhaps this sounds convoluted, but it turned out to be quite simple, and it preserved the organizational structure of the table.

  • The drawback with this method is that autocomplete will keep separate lists for each row, which may not be a big issue, just puzzling for end-users. Also, submitting as a batch of rows can blow the server's post_max_limit, which in PHP means it throws the data away. That can be a serious issue if your interface allows the user to add rows to the table. – Peter Brand Aug 10 '15 at 10:47
1

Tables are not meant for this, why don't you use <div>'s and CSS?

Harmen
  • 20,974
  • 3
  • 52
  • 74
  • 35
    Tables are not mean to represent tabular data? I'm trying to do an editable grid. – vtortola Oct 27 '10 at 17:39
  • I'm not sure a form counts as data. It will certainly never validate your way because there are specific limits as to what tags must / can follow a or tag
    – Prescott Oct 27 '10 at 17:40
  • 1
    @vtortola the key word is "data". In your example, you are using it to control your input form layout NOT presenting data to the end user. Maybe if you explained what the purpose of the table is, it would be easier to recommend some alternatives. – Waleed Al-Balooshi Oct 27 '10 at 17:41
  • 3
    Most implimentations of editable grid's I've seen use a form wrapped around the table, and then each row might have a save button that will pass a key to the submit action (or use ajax and the form submit doesn't mean much anyway). – Prescott Oct 27 '10 at 17:43
  • 1
    You're *collecting* data, as I wrote it in my late answer. What you're after is `display: table-cell;`, too bad old IE are still around there ... – FelipeAls Oct 27 '10 at 17:43
1

I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.

Prescott
  • 6,982
  • 4
  • 47
  • 67
0

it's as simple as not using a table for markup, as stated by Harmen. You're not displaying data after all, you're collecting data.

I'll take for example the question 23 here: http://accessible.netscouts-ggmbh.eu/en/developer.html#fb1_22_5

On paper, it's good as it is. If you had to display the results, it'd probably be OK.
But you can replace it with ... 4 paragraphs with a label and a select (option's would be the headers of the first line). One paragraph per line, this is far more simple.

FelipeAls
  • 20,411
  • 7
  • 49
  • 71
  • 2
    I believe a grid generally both displays data AND allows for editing. – Eli Oct 27 '10 at 17:48
  • A table is complex stuff in HTML. A form too. I wouldn't try to play with both when there are simpler solutions, it's a recipe for having the worse of both worlds. And I'm not talking about a grid (the visual thing), there's (or should be) `display: table-cell;` for that but of the element table with its constraints in HTML. – FelipeAls Oct 27 '10 at 18:32