Tharindu Sandeepa Tharindu Sandeepa - 5 months ago 10
jQuery Question

How to add data to a table dynamically only in html page, like in my sample image

enter image description here

I want to add data to the table only for visual purpose , so that i need to add the user input from those four fields (2 drop-downs selections , and 2 user inputs),by clicking add button, without refreshing the page. (on the fly).No server call included , just for the html page

Answer

$(document).ready(function(){

  $('#btnFillTable').on('click', fillTable);

});

function fillTable(){
// get values form dropdown and text boxes
var a1Value = $('#A1').val();
var a2Value = $('#A2').val();
var b1Value = $('#B1').val();
var b2Value = $('#B2').val();

var rowHtml = '<tr><td>'+a1Value +'</td><td>'+a2Value +'</td><td>'+b1Value +'</td><td>'+b2Value +'</td></tr>';

// lets suppose table id is 'tblViewRecords'

$('#tblViewRecords tbody').append(rowHtml);
  }
#tblViewRecords th{
  text-align:left;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="A1">
  <option value="First">First</option>
  <option value="Second">Second</option>
  <option value="Third">Third</option>
</select>
<select id="A2">
    <option value="First">First</option>
  <option value="Second">Second</option>
  <option value="Third">Third</option>
</select>
<input id="B1" />
<input id="B2" />
<button type="button" id="btnFillTable">Add Entry</button>
<br>
<hr>
<table id="tblViewRecords" width="100%">
  <thead>
    <tr>
    <th>B1</th>
    <th>B2</th>
    <th>A1</th>
    <th>A2</th>
      </tr>
    </thead>
  <tbody></tbody>
</table>

`