Saeed Ramezani
Saeed Ramezani

Reputation: 482

auto add element to table in html

I have three input list and a submit button in a form. there is a table under the form too. I want when I click the submit button, see my input values in the table without reloading page.

<input name="Choose1">
<input name="Choose2">
<input name="Choose3">
<input type="submit" value"Add">

<table>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</table>

it's clear that at first table should be empty. add I should add an element for many times

Upvotes: 1

Views: 970

Answers (2)

Maxime Girou
Maxime Girou

Reputation: 1570

Using jquery

$("#addRow").on('click', function(){
  const html = "<tr><td>"+$('#td1').val()+"</td><td>"+$('#td2').val()+"</td><td>"+$('#td3').val()+"</td></tr>";
  $('#bodyTable').append(html)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="Choose1" id="td1">
<input name="Choose2" id="td2">
<input name="Choose3" id="td3">
<button id="addRow" >Add </button>

<table>
  <thead>
  <tr>
    <th>Field 1</th>
    <th>Field 2</th>
    <th>Field 3</th>
  </tr>
  </thead>
  <tbody id="bodyTable">
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>
    <td>Value 3</td>
  </tr>
  </tbody>
</table>

Upvotes: 3

Muhammad Aftab
Muhammad Aftab

Reputation: 1118

Assign Ids to access the controls and make button type to button:

<input id="Choose1" name="Choose1">
<input id="Choose2" name="Choose2">
<input id="Choose3" name="Choose3">
<input id="btnSubmit" type="button" value"Add">

 <table id="myTable">
    <tr>
        <th>Field 1</th>
        <th>Field 2</th>
        <th>Field 3</th>
    </tr>
  </table>

now add event in jquery:

$(function(){
  $("#btnSubmit").on('click', function(){
    var val1 = $("#Choose1").val();
    var val2 = $("#Choose2").val();
    var val3 = $("#Choose3").val();

  $('#myTable').append('<tr><td>'+ val1  +'</td><td>'+ val2  +'</td><td>'+ val3  +'</td></tr>');

  });
})

Upvotes: 2

Related Questions