Skip to content Skip to sidebar Skip to footer

Copy A Table Row Of Design Html

I want the moment you click on 'create row', line 2 is duplicated with the formatting rule: input, select .. In addition to the first column I want each time to exceed a count of +

Solution 1:

A fast and easy solution (though maybe not best for long term use) is to have a global variable called something like "depth", start it at let depth = 0 then every time you add a line depth++;, if you remove a line only let it remove the line if(depth >= 0) then you will never be deleting the starting line that already exists.

Another way to do it, and maybe more scalable if this is for a bigger project, is to keep track of the number of lines in an array, each time you add a line, you arr.push(line); when you remove a line you arr.splice(indexofline,1); This gives you the ability to not just track what line you're at, but you could also push information about the line that you could use in later code for expanding the program.

Solution 2:

You have some problems in your code.

  • First of all HTML IDs have to be unique. You are using multiple identical IDs.
  • Some input fields have the same name. This does not have to be a problem by all means, however, many server-side script languages (e.g. PHP) just overwrite multiple usages and expose just the last one. PHP forms arrays if you use names like <input name="firstname[]">.
  • A non-empty <title>My Title</title> tag is mandatory in HTML5.

Further more

  • Documents should declare the charset they are encoded with.
  • It is always a good idea to have an <html> tag with a lang attribute.
  • Avoid inline styles. Use stylesheets instead.
  • Inline event handlers like onclick are old-school. Apply event listeners instead.
  • There are semantical senseless <div> elements in the cells.
  • <fieldset> elements containing only one field do not make semantical sense, especially when they devide two related dates. A fieldset enclosing both dates within the same cell could make sense. Use css outline or similar to get the visual effect if you need it.

To get a copy of another row, you can use the cloneNode method.

The number of rows can be determined with table.rows.length. You can use it to fill the 'number count' cell.

If you do need IDs for some reason, they have to be unique per document. This means, you need different IDs even in each row. When copying, you have to change the id in some way - e.g. append the row number.

I have added some demo <label> just to illustrate how to change necessary IDs and the label's for Attribute which is connected to the ID of the according form field. Of course a label in a column with a caption does not really make sense - it's only for teaching purposes.

Copying the first row might be a bad choice, since the entered values are copied as well. More common would be to copy the last entered row. However, there is another alternative. You can use a clean template. <template> elements are not rendered by the browser and thus they are not part of the DOM. You get DOM-like access via the content property.

document.addEventListener('DOMContentLoaded', evt =>
{
  const
    minRowsPreserved = 2,
    byId             = document.getElementById.bind(document)
  ;

  functionmyCreateFunction()
  {
    let
      table    = byId("myTable"),
      rowCount = table.rows.length,
      row      = byId('tpl-row').content.firstElementChild.cloneNode(true)
    ;

    // In case you need IDs: Append the row number seperated by '-' to each ID since IDs must be unique.
    row.querySelectorAll('[id]').forEach(e => e.id += '-' + rowCount);
    // Similar for clickable labels depending on IDs, however, there is no shortcut for the `for` attribute.
    row.querySelectorAll('label[for]').forEach(e => e.setAttribute('for', e.getAttribute('for') + '-' + rowCount));
    // Content of the last cell becomes the row number.
    row.cells[row.cells.length-1].textContent = rowCount;
    // now we append the row to the table body after id-conflicts should be resolved
    table.tBodies[0].appendChild(row);
  }

  functionmyDeleteFunction() {
    let table = byId("myTable");
    if(minRowsPreserved < table.rows.length)
      table.deleteRow(-1);
  }

  byId('btn-create').addEventListener('click', myCreateFunction);
  byId('btn-delete').addEventListener('click', myDeleteFunction);

  // add a first row on startmyCreateFunction();
})
#myTable
{
  font-size    : 12px;
  font-family  : Arial;
  border       : 1px solid black;
  text-align   : center;
  margin-bottom: 2em;
}

#myTabletd
{
  border : 1px solid black;
  padding: 0.4rem;
}

#myTableth
{
  text-align: right;
}

#myTableinput,
#myTable select
{
  font  : 12px'Fira Sans', sans-serif;
}

#myTableinput[type="text"]   { text-align     : right;  }
#myTableinput[type="number"] { text-align-last: center; }
#myTable select               { text-align-last: right;  }

#myTableinput[type="date"]   { width          : 113px;  }
.num1input             { width          : 31px;   }
.first-nameinput             { width          : 55px;   }
.last-nameinput             { width          : 52px;   }
<!DOCTYPE html><htmllang="he"><head><metacharset="UTF-8"><title>dynamic table form</title><body><formmethod="post"><tableid="myTable"class="table table-bordered table-hover"><thead><tr><th>השתתפות / שוברים</th><th>סכ"ה ימים</th><th>עד תאריך</th><th>מתאריך</th><th>שם משפחה</th><th>שם פרטי</th><th>מ.א</th><th>number count</th></tr></thead><tbody></tbody></table></form><buttonid="btn-create">Create row</button><buttonid="btn-delete">Delete row</button><templateid="tpl-row"><trclass="warning"><tdclass="car"><selectid="car"name="car[]"style="width: 94px; text-align-last: right;"><optionvalue="volvo">השתתפות</option><optionvalue="saab">שוברים</option></select></td><tdclass="num1"      ><inputtype="number"id="num1"name="num1[]"      ></td><tdclass="trip-start"><inputtype="date"id="trip-start"name="tripstart[]" ></td><tdclass="trip-end"  ><inputtype="date"id="trip-end"name="tripend[]"   ></td><tdclass="first-name"><inputtype="text"id="first-name"name="firstname[]" ></td><tdclass="last-name" ><inputtype="text"id="last-name"name="lastname[]"  ></td><tdclass="check"><labelfor="num2">demo label:</label><inputtype="number"id="num2"name="num2[]"style="width: 64px; text-align-last: center;"></td><td></td></tr></template>

Post a Comment for "Copy A Table Row Of Design Html"