Creating a user-friendly interface with Dropdown menus paired with Labels and Buttons, structured to repeat row by row

I have a query regarding my design.

My concern is about adding products to the bill. Each product needs to be added on a separate line. View Image of Adding One Product per Line

Upon adding a product, I also want to display its warranty in the Warranty column:

Check Warranty Display for Selected Product

However, when adding subsequent products, I'm struggling to display their warranties. Unable to Show Warranty for Additional Products

The HTML code where dropdown options are populated dynamically:

<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
    <tr class="text-center">
        <td>
            <select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
                <option disabled selected value="">Select Product</option>
                <option id="1" value="31/01/2020">Product #1</option>
                <option id="2" value="31/01/2030">Product #2</option>
                <option id="3" value="31/01/2040">Product #3</option>
            </select>
        </td>
        <td>
            <input name="txtbox" type="text" id="txtbox" />
        </td>
        <td>
            <button type="button" class="btn btn-danger btn-xs disabled">
                <i class="fa fa-times"></i>
            </button>
        </td>
    </tr>
</tbody>

Javascript function for adding rows to the bill:

$(document).ready(function () {
    var counter = 0;
    $("#addrow").on("click", function () {
        var newRow = $("<tr class='text-center'>");
        var cols = "";
        cols += '<td><select name="bill_product[]"><option disabled selected value="">Select Product</option><cms:pages masterpage="product.php"><option value="<cms:show k_page_id />"><cms:show k_page_title /></option></cms:pages></select></td>';
        cols += '<td><input type="text" id="txtbox" name="txtbox" /></td>';
        cols += '<td><button type="button" class="ibtnDel btn btn-danger btn-xs"><i class="fa fa-times"></i></button></td>';
        newRow.append(cols);
        $("table.order-list").append(newRow);
            counter++;
        });
        $("table.order-list").on("click", ".ibtnDel", function (event) {
            $(this).closest("tr").remove();       
                counter -= 1
            });
        });

Code snippet for displaying the warranty end date:

$(document).ready(function() {
    $("#myDropdown").change(function() {
        var selectedValue = $(this).val();
        $("#txtbox").val(selectedValue);
    });
});

Challenge: I'm facing difficulty in showing the warranty date for any product after the first one.

Your assistance would be greatly appreciated.

P.S.: The dynamic values for select option tags are fetched using CouchCMS.

Answer №1

My innovative solution eliminates non-native JS for compatibility with any system:

<tbody style="border: 1px solid rgba(0,0,0,0.35); height: 34px; line-height: 34px;">
    <tr class="text-center">
        <td>
            <select id="myDropdown" name="bill_product[]" onChange="dropdownTip(this.value)">
                <option disabled selected value="">Select Product</option>
                <option id="1" value="31/01/2020">Product #1</option>
                <option id="2" value="31/01/2030">Product #2</option>
                <option id="3" value="31/01/2040">Product #3</option>
            </select>
        </td>
        <td>
            <input name="txtbox" type="text" id="txtbox" />
        </td>
        <td>
            <button type="button" class="btn btn-danger btn-xs disabled">
                Delete
            </button>
        </td>
    </tr>
</tbody>
// Removing lines
let delBtns = document.querySelectorAll(".del-btn");

[].forEach.call(delBtns, function(delBtn){
    delBtn.addEventListener('click', function(event){
    let line = event.target.dataset.line;

    let lineToRemove = document.querySelector("#line-"+line);

    lineToRemove.remove();
  })
});

// Updating inputs
let productDropDowns = document.querySelectorAll("select");

[].forEach.call(productDropDowns, function(dropDown){
    dropDown.addEventListener('change', function(event){
    let line = event.target.dataset.line;

    document.querySelector('#line-'+line+' input').value = event.target.value;
  })
});

// New line button
let count = 0;
let newLineButton = document.querySelector("#newLineTrigger");

newLineButton.addEventListener('click', function(){
    count++;
    let tableBody = document.querySelector('tbody');
  let newLine = document.createElement('tr');
  newLine.id = 'line-' + count;
  tableBody.appendChild(newLine);
  newLine = document.querySelector('#line-' + count);

  let col1 = document.createElement('td');
    let select = document.createElement('select');
  select.id = 'drop' + count;
  select.dataset.line = count;

  select.addEventListener('change', function(event){
    let line = event.target.dataset.line;
    document.querySelector('#line-'+line+' input').value = event.target.value;
  })

  for(let i=0; i<3; i++){
    let option = document.createElement('option');
    option.value = i;
    option.innerText = 'option ' + i;
    select.appendChild(option);
  }

    col1.appendChild(select);

  let col2 = document.createElement('td');
  let textBox = document.createElement('input');
  textBox.id = 'textBox'+count;
  textBox.name = 'textBox'+count;
  col2.appendChild(textBox);

  let col3 = document.createElement('td');
  let newDelBtn = document.createElement('button');
  newDelBtn.className = "del-btn";
  newDelBtn.dataset.line = count;
  newDelBtn.innerText = "Delete";
  newDelBtn.addEventListener('click', function(event){
    let line = event.target.dataset.line;

    let lineToRemove = newLine;

    lineToRemove.remove();
  });
  col3.appendChild(newDelBtn);


    newLine.appendChild(col1);
    newLine.appendChild(col2);
    newLine.appendChild(col3);

  tableBody.appendChild(newLine);
});

Answer №2

The element '#addrow' responsible for adding rows is not visible to me. Could you please modify the fiddle to include this button?

Answer №3

All warranty input fields have the same ID, "txtbox". To differentiate them, you can utilize the counter variable to assign unique IDs to each warranty field.

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

Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller. angular.module(&a ...

Is a webpage's sluggishness in Internet Explorer due to its lengthy page structure causing issues while loading quickly on other browsers?

My application has a page that is particularly long, around 8Mb of source HTML mainly comprised of tables. I am aware that this indicates poor architecture, but unfortunately, I am unable to make immediate changes due to certain constraints. In most brows ...

Creating a tailored regular expression for validating email addresses

Up to this point, I have crafted a regex pattern as Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$" that meets the following criteria: Not all characters should be numbers, ...

Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet: $scope.Get = function () { var EService = [{ id: $scope.Id, ...

Could anyone provide an explanation of the current situation in this section of the code?

I am currently working on a piece of code that looks like this: ruter.get('/', async function (_, res) { const [categories, items] = (await Promise.all([ db.query('SELECT * FROM categories'), db.query('SELECT * FROM invento ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

Revise the reply within ExpressJS

I need help with editing the response to a request in Express. When the request is made via XHR, I want to encapsulate the body inside a JavaScript object. This way, different parts of the page can be accessed individually within the JavaScript object, suc ...

How does gray-matter function in Node.js affect the matter within?

import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; const postsDirectory = path.join(process.cwd(), 'posts'); // ... ... ... // export function getPostData(id) { const fullPath = ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

The maskedinput plugin offered by jQuery

Is there a way to restrict an HTML input field to only accept input in the following format: Name 1 & Name 2, This means that users can only enter two names in the format like for example, "Steven & Peter" or "Alex & Jennifer". I attempted using jQuery ...

Do flexible layouts require more effort and time to create and upkeep compared to fixed width layouts?

Are flexible layouts more challenging to create and maintain than fixed width layouts, and do they take longer to design? Does a flexible layout only involve setting the width, height, and font size in em or %? What are the main advantages of using a fle ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

The addClass function in jQuery does not seem to be functioning properly when used within

I've run into an issue with my jQuery addClass function in a loop. It's supposed to turn my Font Awesome star golden, but for some reason, it's not working as expected. The loop itself is functioning properly - I double-checked this by using ...

Guide to modifying the class color using javascript

I am experiencing an issue with this particular code. I have successfully used getElementById, but when I try to use document.getElementsByClassName("hearts");, it does not work as expected. This is a snippet of my HTML code: status = 1; function change ...

Is it possible for an Android webview to access the device's geo location?

For the application I'm working on, it's necessary to access the user's geo location. We've created a HTML 5 based website and are using a webview to develop our mobile application by calling the website URL. With the latest geo tags av ...

Exploring Android Webview capabilities using HTML 5 geolocation

Utilizing a webview to load a web application, I am using the HTML 5 geolocation API within the page to detect the user's location. While this feature works seamlessly in all browsers and even in an iOS application, I am facing issues getting it to fu ...

Unraveling the JSON section within a intricate text document

Embarking on the development of a desktop application using Electron, I aim to parse files and present data extracted from these complex files. These files contain intricate information. My current challenge involves extracting JSON data from a convoluted ...

Unable to transform data types

Currently, I am studying the JavaScript for automation session at WWDC. Here is an example taken from slide 99 that I am working on. On a fresh installation of Yosemite, I encountered an error on line 3. Safari = Application('Safari') doc = Safa ...

Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to eff ...