Duplicating an element in an array using JavaScript

My view model is structured as follows

 public class ItemViewModel
    {
        [Required]
        public int Id { get; set; }
        [Required]
        public int JobId { get; set; }
        public string ItemId { get; set; }
        public string ItemName { get; set; }
        public IList<ItemPartViewModel> Parts { get; set; }
    }

The ItemViewModel includes an IList of Parts with the following structure

 public class ItemPartViewModel
    {
        [Required]
        public int ID { get; set; }
        public int ItemID { get; set; }
        public string PartID { get; set; }
        public string PartName { get; set; }
        public float QtyInItem { get; set; }
        public float Qty { get; set; }
        public bool MoveAll { get; set; }
        // Additional property for user picks: harvest/transfer/dispose
        public PartActionType SelectedActionType { get; set; }
    }

In display table, if 'moveAll' option in row unchecked, row is cloned to track user actions such as transferring and disposing parts

JavaScript snippet to clone rows:</p>
$(document).ready(function () {
            $('.tr_clonePart input.part-class').change(function () {

                let Id = $(this).attr('id');
                let partId = $(this).attr('data-partId');
                var selector = $(this).closest('.tr_clonePart');
                if ($(this).prop("checked") == true){
                    $('#' + Id + 'clone').remove();
                    selector.find(".AllTxt").show();
                    selector.find(".editQty").hide();
                }
                else {
                    var $tr = $(this).closest('.tr_clonePart');
                    var $clone = $tr.clone();
                    ...
                }

            });

Setup of a single row:

<tr class="tr_clonePart">
   <td>
       @part.PartIDLink
   </td>
   <td>
       @Html.DisplayFor(x => x.Parts[i].PartName)
       @Html.HiddenFor(x => x.Parts[i].PartName)
   </td>
   ...
</tr>

View image for more clarity: https://i.sstatic.net/D0AOe.png

To handle multiple user actions within the same row in the part list, you can extend the cloning logic to reflect each action accurately.

Make adjustments to ensure complete tracking of all user actions across the part list rows.

Answer №1

You have the option to assign a class to the duplicated row, distinguishing it from the original and cloned rows. In the code snippet below, I utilized the part_id to differentiate between them. Additionally, each input has been assigned a class for easier value retrieval. To transmit these values collectively (both cloned and original), a JSON Array was constructed since the values for all inputs remain identical, with only the quantity and actiontype changing. To preserve these values, arrays were generated. Subsequently, you can dispatch the resulting JSON Array to your backend using ajax.

Demo code:

$('.tr_clonePart input.part-class').change(function() {
  let Id = $(this).attr('id');
  let partId = $(this).attr('data-partId');
  //getting closest tr
  var selector = $(this).closest('.tr_clonePart');
  //get original radio 
  var radios_old = selector.find("input[type='radio']:checked");
 ...
</button>

On the backend side, simply adjust the datatype of Qty to an array and introduce a new field for actionType as an array to store the input and radio button values.

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

Decrease the size of the mat-flat-button

I have a message board where I am trying to incorporate delete buttons. However, when using the mat-flat-button feature, it appears to be increasing the height of the message items. If I adjust the button's height to 50%, then the button becomes half ...

Is your NextJS Link component failing to redirect correctly?

I'm currently delving into Next.js and embarking on a small experimental project to get more comfortable with it. However, I'm having some issues with the Link tag. It does redirect me to the specified friends page, but for some reason, the conte ...

The jsonp typeahead feature is not populating the uib-typeahead form element

Trying to populate a uib-typeahead from the ui-bootstrap modules using a jsonp callback function in a factory method has been challenging. This is the factory function being used: autoCompleteCity: function(city){ return $http.jsonp("http://g ...

Just work seamlessly with comparable features

Is there a more efficient way to simplify this function? I am faced with multiple tweens that share similar ease properties. While I acknowledge the broad nature of this query, I have yet to discover a satisfactory solution. $('input').chan ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

Zod: Generate a basic item using default settings

I have a strong belief that this concept exists, however, my research has not yielded any results. Let's consider a scenario where I have a zod Schema structured like this: const Person = zod.object({ name: z.string().default(''), ag ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

Objects cannot be rendered inside JSX. An error is thrown stating that Objects are not allowed as a React child, with the specific object being [object Promise]

Within my React project, I have a Class-based component that serves as a child component. The state it relies on is passed down from a parent component. Within the JSX of this component, there is a map function that iterates over a platformsList array. Whi ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...

Submitting JSON data from React to a C# WebApi

I am facing an issue with my C# WebAPI action. I am attempting to send a JSON string to it using React. However, when I set the content type as application/json, I receive a 405 Method Not Allowed error. Sending the data as urlencoded works and gets into ...

Importing types from a private npm module with FlowTypes

Currently I am in the process of developing a private npm package for internal use. One challenge I am facing is how to include flowtypes that can be shared across different internal projects. Ideally, I would like these flowtypes to be imported in the for ...

What is the best way to get rid of a Bootstrap modal?

Currently, I am working on a small application to enhance my knowledge of AJAX and JavaScript. Within this project, I have implemented a method called saveData() which is activated upon clicking a 'save' button. Everything seemed to be functionin ...

Convert a Bytes Array to an Object using JSON.Net

I am currently working on deserializing a large amount of data from a JSON file in order to improve performance. While researching ways to increase efficiency, I came across suggestions to read the bytes directly and deserialize them without converting to ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

What's the best way to begin printing a StringListProperty() starting at index [1]?

I am working on a model class Category(db.Model): merchandise = db.StringListProperty() content = db.StringListProperty() topics = db.StringListProperty() For example, if the merchandise list is ["merchandise","tshirt","book","poster"] ...

Triggering an event with two clicks in JQuery

I'm facing an issue with firing 2 click events in jQuery to remove files when a RadioBoxList is selected. The buttons on the page are calling the same function as delete_Click in the code behind. Here is my current code: <asp:Button ID="delBtn1" ...

"Is there a way to dynamically add an input value as a class to the currently selected element using jQuery

Hey everyone, I'm currently working on some jQuery code to change the class of an icon by selecting a radio input with the corresponding class value. However, I'm encountering an issue where the class value is being added to all other icons as we ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...

When transmitting data from the parent component to the child component, the data successfully passes through, yet the view fails to reflect the

I'm facing an issue with passing data from a parent component to a child component using props. Here is the code snippet I'm working with: <div id="root"> <my-component v-bind:account-types='accountTypes'> </my-c ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...