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

Execute command problem

Explaining this code may be a bit tricky, but I'll do my best. Below is the code snippet for executing a slash command. client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; const command = c ...

How to conditionally prevent event propagation to children in VueJs

This Vue component is called ColorButtonGroup, and it serves as a group of checkbox/toggle buttons. It has a maximum limit of 4 colors that can be selected. The component utilizes another component called ToggleButton, which is a simple toggle selection w ...

Google Cloud Endpoints API Encounter 404 Error

Scenario Currently, my setup involves AppEngine Cloud Endpoints using a Bootstrap JavaScript UI along with a Google SQL Datastore. Issue The problem arises when the Javascript tries to call gapi.client.load and receives a 404 error. Surprisingly, the ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

How can we stop a form from being submitted when the input field is

Similar Question: How to prevent submitting the HTML form’s input field value if it empty <?php include '../core/init.php'; if(isset($_POST['nt']) && isset($_POST['ntb'])){ mysql_query("INSERT INTO `pos ...

Wrap all temporary array elements of the same type within an object

Extracted from a json api, the following snippet of content showcases various titles and content types: contents: [ { title: "some title", content_type: 2 }, { title: "some title", content_type: 2 }, { title: "some title", content_type: 1 }, { title: ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

I developed an RPG game with an interactive element using jQuery. One of the biggest challenges I'm facing is the random selection process for determining which hero will be targeted by the enemy bots during battles

Hello, this marks my debut on stack overflow with a question. I've created a game inspired by old school RPGs where players choose from three heroes based on the Marvel universe to battle one of three enemies. The problem I'm facing is that even ...

What is the best way to use CSS to center two blocks with space in between them?

My goal is to achieve a specific design: I want two text blocks with some space in between them aligned around the midline of the page (refer to the image). I have experimented with the float property, as well as used margin and padding to create the gap ...

"Step-by-step guide to building a webgrid or table to organize and display your

These are the HTML codes I have created: <table> <tr> <td><label style="text-align:left">Product Code:</label></td> <td><input type="text" id="productCode" value="" /> </td> </tr> & ...

The iPhone header position switches when an HTML5 input type number is selected

I am currently working on a project that involves jQuery Mobile and PhoneGap. One issue I am encountering is when using the iPhone version, the header position changes when I click on an input type number. NOTE: When I focus on the input type number in my ...

The appearance of HTML in JSP and CSS output in a Spring application is different from the local environment

For my web application's landing page, I created the design using HTML and CSS. Typically, I first design it on scratchpad.io before implementing it into my STS IDE. However, when I run the application, the output of the page appears different from th ...

Working with AngularJS's $q promise and socket.io

I am interested in creating an angularJS promise that can work seamlessly with socket.io. Currently, I have a callback function set up to handle the response like this: function request(event, data, callback) { socket.emit(event, data); socket.on( ...

Whenever I navigate to this specific route, I consistently encounter an error message in my console

VM28353:1 Error: Unexpected token 'o' found in JSON at position 1 at JSON.parse (<anonymous>) at getUser (auth.js?c7d4:11) at wrappedGetter (vuex.esm-browser.js?5502:335) at Object.eval [as getUser] (vuex.esm-browser.js?5502 ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

Achieving full table height with a parent having a min-height requirement

Encountering a seemingly straightforward issue where I am unable to make an inner div 100% height of the parent div, which is set with min-height 70vh. My goal is to have the table inside be 100% height and content vertically aligned. It currently works if ...

Tips for adjusting the font size options within the Autocomplete feature of Material UI Version 5

Is there a way to adjust the font size of the drop-down items? I have tried various methods to change the font size, including: How do I change Material UI Autocomplete font size? How to change fontsize of options in Material ui autocomplete? Unfortuna ...