Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a simple dynamic grid

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
US
I am trying to create a simple javascript Grid but I can't seem to find any simple solutions.

Here is what I am trying to do, on a webpage I want users to be able to add as many part numbers , description for each item and a date. So basically it looks like this -

Code:
Part Number    Descrption  Date
A1100            Part A    01/01/05
BAE1223          Part B    02/02/05

My problem is I am not sure how many items will added upfront and there is no fixed number. Also when the user hits submits all the information is stored in a table so each row has to be uniqe.
 
Try this:
Code:
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;

  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // first cell
  var cell1 = row.insertCell(0);
  var el = document.createElement('input');
  el.setAttribute('type', 'text');
  el.setAttribute('name', 'partnum' + iteration);
  el.setAttribute('id', 'partnum' + iteration);
  el.onkeypress = keyPressTest;
  cell1.appendChild(el);
  
  // second cell
  var cell2 = row.insertCell(1);
  var el = document.createElement('input');
  el.setAttribute('type', 'text');
  el.setAttribute('name', 'description' + iteration);
  el.setAttribute('id', 'description' + iteration);
  el.setAttribute('size', '40');
  el.onkeypress = keyPressTest;
  cell2.appendChild(el);

  // third cell
  var cell3 = row.insertCell(2);
  var el = document.createElement('input');
  el.setAttribute('type', 'text');
  el.setAttribute('name', 'mydate' + iteration);
  el.setAttribute('id', 'mydate' + iteration);
  el.setAttribute('size', '40');
  el.onkeypress = keyPressTest;
  cell3.appendChild(el);
}

And this:
Code:
function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 1) tbl.deleteRow(lastRow - 1);
}

And this:
Code:
<form action="tableaddrow_nw.html" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
</p>
<p>
<input type="checkbox" id="chkValidateOnKeyPress" checked="checked" /> Display OnKeyPress
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
  <tr>
    <td width="265">&nbsp;</td>
    <td width="265" align="center">Sample table</td>
    <td width="265">&nbsp;</td>
  </tr>
<!--
  <tr>
    <td><input type="text" name="partnum1" id="partnum1" size="40" onkeypress="keyPressTest(event, this);" /></td>
    <td><input type="text" name="description1" id="description1" size="40" onkeypress="keyPressTest(event, this);" /></td>
    <td><input type="text" name="mydate1" id="mydate1" size="40" onkeypress="keyPressTest(event, this);" /></td>
  </tr>
-->
</table>
</form>

I commented out the table row that was added in. You can uncomment it if you want them there.
The way the script is setup it always starts the first row to be created with the number 1 appended to the ID and Name attributes.

My suggestion, if people are going to be entering this information I would put an input box at the bottom of the page that they type the description into and then hit a button that adds it into the table rather than adding a row and then typing the information into the fields directly. This way you can do your field validation before it even creates the table row so you have less cleanup on the table to do if for some reason the data entered does not fit your requirements.

Also, rather than having a delete button for the rows as it does now, you would want to be able to selectively delete any row. My suggestion would be to have yet another cell at the beginning of the row with DEL as the text and have it set to call the delete function passing that row number and then deleting the specific row instead of just the last one created.

I am sure you will rethink this quite a bit as you begin messing around with it and realize how differently you actually need it to work for your purposes. But this is a good code for you to get the idea of how to create and remove DOM elements.

If you need, I can try and dig up an example of a more sophisticated add/remove script I created for an app at work.


Paranoid? ME?? WHO WANTS TO KNOW????
 
countdrak, here is an early holiday gift for you.

This code produces a 4 field table, the first field containing a link allowing the deletion of a that particular row. Then it displays Part number, Description and Date as you originally requested.

The script is setup with a listbox to select items to add into the table. This can be changed to anything you like but I assumed that the options that would be selected would be of a fixed type not something the person would be typing in freely. If you want them to add things freely you can replace the listbox with an input fields and an Add button.
I also did not know where you pulled the date from so I set it up to grab todays date. All of this is easily modified for whatever use you actually have for it.

The approach is quite a bit different than the original code you were looking at. The reason being, if you need to remove something that had been added to the list you would have no way of knowing on the next code page which form fields no longer existed.
This approach writes the data into an array first then rebuilds the table to display the updated information. The table only contains text, not actual input fields.
When you have selected all the items you want and hit the submit button the code will create hidden fields with sequential names and write the data into those fields.
It will also put the total number of data fields into another hidden field so on your next page you can tell how many fields you need to loop through.

Let me know how it works for you.
Code:
<html>
<head>
<title></title>
<style>
.delcell {
border-style: solid;
border-color: #000000;
border-bottom-width: 1px;
border-left-width: 0px;
border-right-width: 0px;
border-top-width: 0px;
}
.partcell {
border-style: solid;
border-color: #000000;
border-bottom-width: 1px;
border-left-width: 1px;
border-right-width: 1px;
border-top-width: 1px;
}
</style>
<script language="javascript">
var arrParts = new Array();

function addrow(which)
{
  if (which.value != 0)
  { //Add value and text from listbox as well as current date to the arrParts array.
    var today = new Date();
    var year = today.getYear()     
    var shortdate = ((today.getMonth()+1) + "/" + today.getDate() + "/" + (year+"").substring(2,4));
    var arrRow = arrParts.length;
    arrParts[arrRow] = which.value;
    arrParts[arrRow+1] = (which.options(which.selectedIndex).text);
    arrParts[arrRow+2] = shortdate;
    showtable();
  }
}

function showtable()
{ //Removes existing rows of data from table and then rebuilds the table with updated info from arrParts.
  var lastRow = 2; //Starts at 2 so the title and header rows do not get deleted.
  var mytable = document.getElementById('SelectedParts');

  //First, remove all previously created cells except the title and headers.
  var delRows = mytable.rows.length;
  for (var loop=delRows;loop>2;loop--)
  {
    mytable.deleteRow(loop-1);
  }

  //Now rebuild the rows with information from arrParts.
  if (arrParts.length / 3 >= 2)
    var arrlength = (arrParts.length / 3) - 1;
  else
    arrlength = 0;
  for (loop=0;loop<arrParts.length;loop++)
  {
    var row = mytable.insertRow(lastRow);
    var delrow='<font color="#0000A0"><a onmouseover="this.style.cursor=\'hand\'; this.style.color=\'red\'" onmouseout="this.style.cursor=\'auto\'; this.style.color=\'0000A0\';" onclick="removerow(' + loop + ');">Del</a></font>&nbsp;&nbsp;';

    // first cell
    var cell1 = row.insertCell(0);
    cell1.innerHTML=delrow;
    cell1.setAttribute("className", "delcell");

    // second cell
    var cell2 = row.insertCell(1);
    cell2.innerText=arrParts[loop];
    cell2.setAttribute("className", "partcell");
 
    // third cell
    var cell3 = row.insertCell(2);
    cell3.innerText=arrParts[loop+1];
    cell3.setAttribute("className", "partcell");

    // fourth cell
    var cell4 = row.insertCell(3);
    cell4.innerText=arrParts[loop+2];
    cell4.setAttribute("className", "partcell");

    lastRow++;
    loop=loop+2;
  }
}

function removerow(which)
{ //Remove row of data from arrParts when Del is selected next to that row in table.
  var whichrow = 
  arrParts.splice(which, 3);
  showtable();
}

function createhidden()
{ //Create hidden Input fields for selected data before submitting form.
  //Fields are named Partsx with x representing the array position the data came from.  
  //Each record contains 3 pieces of data, Part number, description and date.  Arrays start at 0.
  //So the first record will be contained in hidden fields Part0, Part1 and Part2.  This makes it easy
  //to read the fields dynamically from the script you post this data to.
  //The total number of hidden Parts fields created will be stored in field HiddenTotal so you know how much
  //data to read in on the next page.  This value also starts at 0 so a value of 8 means there are 9 fields to read.
  var myform = document.getElementById('SubmitData');
  document.getElementById('HiddenTotal').value = arrParts.length-1;
  if (arrParts.length >0)
  {
    for (var loop=0;loop<arrParts.length;loop++)
    {
      var fieldname = "Part" + loop;
      var fileinput = document.createElement("input");
        fileinput.type = "hidden";
        fileinput.id = fieldname;
        fileinput.name = fieldname;
        fileinput.value = arrParts[loop];
      myform.appendChild(fileinput);
    }
  }
}

function isready()
{ //If you place any calls in here to do validation, execute it prior to calling createhidden.
  //Otherwise you might create hidden fields, error so the form does not submit and then when it is submitted
  //again it would create more hidden fields with an identical name.
  createhidden();  //Create hidden fields before submitting.
  return true;  //Allow form to submit.  Setting to false will prevent submission.
}
</script>
<body>
<div align="center">
<form id="SubmitData" method="post" action="mypage.asp" onsubmit="return isready()" >
<input id="HiddenTotal" type="hidden" value="">
<table id="SelectedParts" border="0" width="600" cellspacing="0" cellpadding="0">
  <tr>
    <td width="600" colspan="4" style="text-align: center; font-weight: bold">Part Selection</td>
  </tr>
  <tr>
    <td width="40"></td>
    <td width="150"
    style="text-align: center; font-weight: bold; border: 1px solid rgb(0,0,0)">Part Number</td>
    <td width="260"
    style="text-align: center; font-weight: bold; border: 1px solid rgb(0,0,0)">Description</td>
    <td width="150"
    style="text-align: center; font-weight: bold; border: 1px solid rgb(0,0,0)">Date</td>
  </tr>
</table>
</center>

<table border="0" width="600" align="center">
  <tr>
    <td height="15"></td>
  </tr>
  <tr>
    <td align="center"><select name="PartsList" size="1" onchange="addrow(this)">
      <option value="0">Select a Part</option>
      <option value="1001">Part1</option>
      <option value="1002">Part2</option>
      <option value="1003">Part3</option>
      <option value="1004">Part4</option>
      <option value="1005">Part5</option>
    </select> </td>
  </tr>
</table>
<br><br>
<center><input type="Submit" value="Submit"></center>
</form>
</center></div>
</body>
</html>

Paranoid? ME?? WHO WANTS TO KNOW????
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top