user0946076422
user0946076422

Reputation: 69

how to create dynamic grid using javascript


s.no. | description

  1. abcd1
  2. abcd2
  3. abcd3

i want to add more rows through input. now what i want is when i will add another row. let say {describtion="abcd4"}

then the above grid will become

s.no. | description

  1. abcd4
  2. abcd1
  3. abcd2
  4. abcd3

meaning s.no. field got updated and new row will be added at top. adding a new row on top is no issue but how could i update s.no. at same time, here i want to ask is there any specific way to do this.

Upvotes: 0

Views: 1147

Answers (3)

Sachin
Sachin

Reputation: 1218

function pushAtStarting(array, element){
    array.unshift(element); // new element has s.no = 0
    for (index in array){
       array[index].sno++
    }
}
var array = [];
pushAtStarting(array, {sno: 0, description: "abc"});

it works if your grid is java script arrays and elements are json elements.

Upvotes: 0

trincot
trincot

Reputation: 351218

Here is a solution that adds rows at the top of a table and keeps the numbers updated:

document.querySelector('#btnadd').addEventListener('click', function () {
  var inp = document.querySelector('#inpadd');
  var descr = inp.value;
  if (descr === '') return; // do not add empty values
  var grid = document.querySelector('#grid');
  // first increment all row numbers
  for (var i = 1, row; row = grid.rows[i]; i++) {
    row.cells[0].textContent = i+1;
  }
  // add new row
  var row = grid.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.textContent = 1;
  cell2.textContent = descr;
  // clear input
  inp.value = "";
});
New description: <input type="text" id="inpadd"><button id="btnadd">Add</button>
<table id="grid">
  <tr><th>s.no.</th><th>description</th></tr>
<table>

Upvotes: 1

Nitin Sinha
Nitin Sinha

Reputation: 179

If you want to insert new text description in the beginning of the ordered list, you can use 'insertBefore' javascript code:

list.insertBefore(entry, list.firstChild);

It should add the new text in the beginning of the list. Refer below code if it helps your problem.

<!DOCTYPE html>
<html>
<body>

<p>Input the text description and click 'Add Description' button to insert in list:</p>

<form>
Description Text:<br>
<input type="text" name="description" id="description">
<br>
<input type="button" value="Add Description" onclick='appendDescription()'>
</form>

<ol id="desclist">
<li>abcd1</li>
<li>abcd2</li>
<li>abcd3</li>
</ol>

<script>
function appendDescription(){
var description= document.getElementById('description').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(description));

var list = document.getElementById('desclist');

list.insertBefore(entry, list.firstChild);
}
</script>
</body>
</html>

Upvotes: 0

Related Questions