Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated!

Example needed:-

https://i.sstatic.net/DF8Wn.png

 $(document).ready(function (){
       $("body").on('click', '.btn-add-more', function (e) {
   e.preventDefault();
   var $sr = ($(".jdr1").length + 1);
   var rowid = Math.random();
   
   var $html = '<tr class="jdr1" id="' + rowid + '">' +
           '<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
           '<td><input type="text" required="" class="form-control input-sm title" placeholder="Medicine" name="medicine[]"></td>' +
           '<td><input type="text" name="medicine_qty[]" placeholder="Potency" class="form-control input-sm"></td>' +
           '<td><input type="text" name="medicine_time[]" placeholder="Description" class="form-control input-sm"></td>' +
           '<td><input type="text" name="remark[]" placeholder="Add/Note" class="form-control input-sm"></td>' + '<td><button class="btn btn-sm btn-warning btn-remove-detail-row"><i class="glyphicon glyphicon-remove">Remove</i></button>    </td>'+
           '</tr>';
   
   $("#table-details").append($html);
   
   });

Answer №1

You have the flexibility to enclose the function within a for loop and adjust the limit of the for loop based on your specific requirements.

$("body").on('click', '.btn-add-more', function (e) {
  e.preventDefault();
  var rows = $(".jdr1").length;
  var limit = 1;
  // Initially append 3 rows on first click, then 1 row per subsequent click
  if (rows < 3) limit = 3;
   for (let i=0; i<limit; i++) {
      var $sr = ($(".jdr1").length + 1);
      var rowid = Math.random();
      var $html = '<tr class="jdr1" id="' + rowid + '">' +
           '<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
           '<td><input type="text" required="" class="form-control input-sm title" placeholder="Medicine" name="medicine[]"></td>' +
           '<td><input type="text" name="medicine_qty[]" placeholder="Potency" class="form-control input-sm"></td>' +
           '<td><input type="text" name="medicine_time[]" placeholder="Description" class="form-control input-sm"></td>' +
           '<td><input type="text" name="remark[]" placeholder="Add/Note" class="form-control input-sm"></td>' + '<td><button class="btn btn-sm btn-warning btn-remove-detail-row"><i class="glyphicon glyphicon-remove">Remove</i></button>    </td>'+
           '</tr>';
   
   $("#table-details").append($html);
   }
})
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<table id="table-details"></table>
<button class="btn-add-more">Add Rows</button>
</html>

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

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

How do I handle the error "Uncaught TypeError: Cannot read property 'func' of undefined in React JS

Hey there, I've encountered an issue while setting up a date picker on my project. I tried using these resources: https://github.com/Eonasdan/bootstrap-datetimepicker Would appreciate any help! https://codesandbox.io/s/18941xp52l render() { ...

Cutting an image in ReactJS using the HTML5 canvas feature

Seeking a way to crop images in reactjs without relying on any external library. The goal is for users to upload an image and perform cropping using raw JavaScript, then replace the uploaded image. How can this be achieved without the use of libraries? Loo ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

Tips on invoking a factory method from a different service method in AngularJS

I have a factory method that goes like this.. (function (angular) { "use strict"; angular .module('app') .factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) { ...

Is there a way to add more order details without having to refresh the page?

As a beginner in Django, I have created a checkout page where the user can change the input range number. However, only the first one seems to be sending data to the server. I suspect this is because I have set the same ID for all inputs and I am unable to ...

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

Calculator for Angular User Input

Looking to create a simple application, I encountered an issue with my if statement. I would greatly appreciate any help in identifying the problem. The goal of the application is to provide users with a text box where they can input comma-separated items ...

Alerting Users Before Navigating Away from an Angular Page

I am looking to implement a feature in my app that will display a warning message when attempting to close the tab, exit the page, or reload it. However, I am facing an issue where the warning message is displayed but the page still exits before I can resp ...

Enhancing the Google canvas script to incorporate numerous markers

Currently, I am using a template that includes a Google map with coordinates set in JavaScript. The code for the marker on the map is as follows: //Google Map var latlng = new google.maps.LatLng(44.761128,21.227395); var settings = { ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...

"Upon successful completion of a jQuery AJAX POST request, data is

Could you help me troubleshoot my code? I can't seem to retrieve my data. Thank you. Index.php <script type="text/javascript> jQuery(document).ready(function(){ $(".click").click(function(){ var value = $(this).val();// sendin ...

Creating a Cubic Bezier Curve connecting two points within a 3D sphere using three.js

I'm currently working on a project where the user can click on two points on a sphere and I want to connect these points with a line along the surface of the sphere, following the great circle path. I have managed to obtain the coordinates of the sele ...

The data received by request.responseText is accurate, however JavaScript is unable to interpret it

I am currently diving into the world of AJAX and educating myself using Head First AJAX. I have encountered a strange issue while working on a simple program that makes a request using JavaScript and displays the output. main.js window.onload = initPage; ...

Incorporating CSS styles into a dynamic JavaScript computation

I'm attempting to apply inline CSS to a JS calculation (e.g. 3*2*1) in order to make it appear red. I have experimented with using a span tag, but it only displays the calculation and not the result. I also tried utilizing an internal style sheet. Ho ...

What is the best approach to developing Vue components with unique templates while maintaining the same functionality without duplicating code?

I am working on a project to develop a custom and versatile datatable component. My goal is to be able to adjust the appearance of the datatable on each page, while maintaining consistent functionality. I want to pass data rows into the component and have ...

Vibrant DT data table featuring vertical radio buttons

I am in need of a polished DT datatable that includes radio buttons embedded within a column. While this application provides a solution for horizontal buttons, I have taken on the task of adapting it for a vertical layout. Modifying the matrix was a strai ...

What causes the slowness of onsubmit=" " function?

Initially, I had the following setup: HTML: <form onsubmit="return validate()"> ... <input type="submit" id="submit-button"/> </form> JS: function validate() { // Extensive validation process with regex and more... $(& ...