Guide on how to append input field data to a table using jQuery

My current project involves working with a table, and I have encountered some challenges along the way. Typically, I have 4 input fields where I can input data that is then sent to the table in my view. However, if I exceed 4 values and need to add more, I have included a button labeled "Plus". This button clears out previous values from the field and prompts the user to input new ones.

Once the "Plus" button is clicked, the data gets added to the table. But interestingly, after pressing the Send to table button, all the data disappears.

Here's a snippet of the code:

$('.coButton').on('click', function() {
  $('.changeoverTable').show();
  var arrNumber = new Array();
  $(".changeoverTable > tbody").html('');
  $('input[type=text]').each(function(i) {

    arrNumber.push($(this).val());
    if (arrNumber[i]) {
      $(".changeoverTable > tbody").append('<tr><td>Data</td><td>' + arrNumber[i] + '</td></tr>');
    }

  })
});
...

...
});
body {
  background: #f5f5f5;
}

.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<center><input type="text" placeholder="Enter number of data"></center>
<center><button class="coButton">Send to table</button></center>
...
...
</table>

Answer №1

Why not give this a try:

function addToList() {
  var name = $("#mytext").val();
  var lastName = $("#lastname").val();
  var anything = $("#any").val();
  $("#mytable tbody").append("<tr><td>" + name + "</td><td>" + lastName + "</td><td>" + anything + "</td></tr>");
  $("#mytext").val('');
  $("#lastname").val('');
  $("#any").val('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="mytext" />
<input type="text" id="lastname" />
<input type="text" id="any" />
<br />
<br />
<input type="submit" value="Submit" onclick="addToList()" id="submit" />
<br />
<br />
<table id="mytable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Last Name</th>
      <th>Anything</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Answer №2

$(document).ready(function(){
    $('.coButton').on('click', function () {
        $('.changeoverTable').show();
        var arrNumber = new Array();
        $(".add").each(function () {
            $(this).remove();
        });
        $('input[type=text]').each(function (i) {

            arrNumber.push($(this).val());
            if (arrNumber[i]) {

                if($(".changeoverTable > tbody > tr").hasClass("add_more")) {
                    $(".changeoverTable > tbody .add_more").first().before('<tr class="add"><td>Data</td><td>' + arrNumber[i] + '</td></tr>');
                }else{
                    $(".changeoverTable > tbody").append('<tr class="add"><td>Data</td><td>' + arrNumber[i] + '</td></tr>');
                }
            
            }

        })
    });

    $('.plusButton').on('click', function () {
        var value = $('#opBarcode').val();
        if(value){
            $(".changeoverTable > tbody").append('<tr class="add_more"><td>Data</td><td>' + value + '</td></tr>');
        }

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <center><input type="text" placeholder="Enter number of data"></center>
    <center><button class="coButton">Send to table</button></center>
    <center><input type="text" id="opBarcode" placeholder="Enter number of layers">
    <button class="plusButton">Plus</button></center>
    <center><button class="coButton">Send to table</button></center>
    <center><input type="text" placeholder="Enter number of nest"></center>
    <center><button class="coButton">Send to table</button></center>
    <center><input type="text" placeholder="Enter number of layers"></center>
    <center><button class="coButton">Send to table</button></center>
    <table class="changeoverTable hide">
        <thead>
            <tr>
                <th colspan="3">Table</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

Answer №3

Make sure to test this code in a jsfiddle to see the magic of adding rows dynamically!

 $(document).ready(function () {
        var myarr = [];
    });
    function appen() {
        var a = $("#mytext").val();
    
        $("#mytable tbody").append("<tr><td>" +a+ "</td></tr>");
        $("#mytext").val('');
        $("#lastname").val('');
        $("#any").val('');
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <input type="text" id="mytext" />
</div>
<br>
<br>
<input type="submit" value="submit" onclick="appen()" id="submit" />

<br />
<br />
<table id="mytable">
    <thead>
        <tr>
            <th>name</th>
  
        </tr>
    </thead>
    <tbody></tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing someone else's codebase up to date from version 49 to the latest version

After fixing the naming errors, I'm still encountering some issues. You can view the expected page layout here: Here is my current progress: There seems to be some glitched triangles when scrolling, and I believe splitting face4's into two fac ...

What is the best way to place a header in a specific location on a

As I continue working on my project, I am facing a challenge in positioning the headings in specific places. My ultimate goal is to achieve a look similar to Figure 1 for my headings. [Figure 1][1] However, as of now, my layout resembles Figure 2. I find ...

Improving the style of Google Maps InfoWindows for right-to-left languages

I'm currently working on a Google Maps marker infowindow and trying to adjust the padding specifically for RTL languages. Here's what I've attempted so far: google.maps.event.addListener(marker, 'click', function () { i ...

Utilize TypoScript to inject HeaderData prior to implementing Style Definitions

My goal is to include my Google Tag Manager script before the style definitions in order to optimize the loading order and prioritize font-family rendering. Currently, I achieve this by: page.includeCSS { file1 = fileadmin/templates/css/bootstrap.css page. ...

Ways to create an oval background for my button

Can someone help me create a button with a unique shape similar to the Products button on stack overflow? Check out this image for reference I attempted using border radius, but it didn't give me the desired effect. I searched for other options but c ...

Modify the CSS borders to reflect a selected radio input type

I'm attempting to change the color of a Radio Button to blue when it's selected, but I'm having trouble achieving this. Here is the CSS code I'm using: /* Radio Button Style */ .radio { padding-left: 25px; } .radio label { di ...

Is it possible to utilize both jQuery and AngularJS in our web application?

Is it feasible to incorporate both jQuery and AngularJS in our web application? Some sources suggest avoiding using them together due to their distinct lifecycles. We need to develop a responsive web application using ASP.NET WebApi and AngularJS. To achi ...

Struggling to make Tumblr Javascript function properly

I have integrated the following code snippet: <script type="text/javascript" src="http://underlineent.tumblr.com/api/read/json"> </script> Unfortunately, my Tumblr blog is not appearing on this site. Can anyone provide assistance? The provid ...

Verify if data already exists in an HTML table column using JavaScript

As a beginner in web programming, I am currently trying to dynamically add data to a table. But before inserting the data into the table, my requirement is to first verify if the data already exists in a specific column, such as the name column. function ...

Firefox is not rendering HTML5 elements properly

While my website performs well in Chrome and Safari, there seems to be an issue with how elements are displayed in Firefox or IE. Some elements are being pushed to the right, and I am unsure of how to fix this problem. You can view the site here To aid i ...

Easily transferring the entire form using jQuery

Here's the code I'm working with: http://jsfiddle.net/aH2qC/ I am currently facing an issue where the code is not functioning as expected. What I need to do is extract the content from the form's action="" attribute and utilize it as the u ...

Issues with the orderBy function are causing unexpected behavior

After creating 3 groups - priority 1, 2, and 3 with orderBy:priorty for each pushed task to go into their designated group, I noticed some strange behavior within the groups where they don't sort properly when more data is added. <input ng-model=" ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Is there a way to make the fixed table header scroll along with the table body data?

I am facing an issue with my table where I have multiple columns. I have managed to fix the table header successfully, however, when I scroll horizontally through the table body columns, the header remains fixed and does not move accordingly. How can I res ...

What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue? import question from './components/Questions.vue'; Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.App = new Vue({ ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Ways to display the name of the month instead of displaying the numerical value of the

The current value in my month variable is 2019-12. <p class="col-md-1"><?php echo $cm['month']; ?></p> I am looking to display the date as DEC 2019. ...

Firefox causing issues with Rails Ajax functionality

My Rails application includes an AJAX call that currently triggers a JavaScript alert message. While this functionality works smoothly on Safari and Chrome, it strangely fails to function on Firefox (across all its recent versions). I tried debugging the c ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

How to align a div in the center of a cell with Bootstrap

I am currently working with Bootstrap 3 and I have a specific requirement to center a div within a cell in the container row. Most resources I found only mention how to center a div within the entire container, which is not what I am looking for. My goal i ...