How to dynamically add table rows and cells with JavaScript using a single selection input

I am working on a project that involves a selection input with around 5 options. Additionally, there is an empty table that follows this format:

<table>
   <tr>
      <td>X (for deletion)</td>
      <td>Option name</td>
      <td>Value linked to the option name</td>
   </tr>
</table>

My goal is to dynamically add a new <tr> element with 3 <td> each time a user selects an option from the menu. The first <td> will display an "X" or image for deleting the row, the second <td> will show the option name, and the third <td> will have a value linked to that option.

I am looking for guidance on how to create a program that can automatically add the <tr> and its <td>s. Additionally, I need help implementing functionality so that when a user clicks on the "X", it deletes the entire parent <tr>. If possible, I would also like suggestions on how to sum up all values in the 3 <td>s and display the total on screen.

It's a lot to ask, but if anyone has any insights or solutions, I would greatly appreciate your help. Thank you for taking the time to read this.

Answer №1

Give this code a try to achieve what you need:

$('button').click(function() {
  $('table').append('<tr><td class="remove">X</td><td class="optionValue">' + $('select option:selected').text() + '</td><td class="linkedValue">' + $('select').val() + '</td></tr>');
})

$(document).on('click', '.remove', function() {
    $(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button type="button">Enter</button>
<br />
<br/>
<table>
  <tr>
    <td>X(for delete)</td>
    <td>Option name</td>
    <td>Value that is linked to that option name</td>
  </tr>
</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

How to align the last item in the bottom row using Flexbox styling

Is it possible to center the last element when resizing the window to a smaller resolution, even though the parent's justify-content parameter is set to space-between? I understand that using center or space-around would achieve the desired result, bu ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

Tips for personalizing your Magento 2 theme

As someone new to Magento 2 and front-end development with a basic knowledge of HTML and CSS, I am eager to customize the blank theme in Magento 2 to gain a deeper understanding of how things work. However, despite reading through the documentation, I am u ...

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

How to sort Firebase real-time database by the child node with the highest number of

I am working on a database feature that allows users to 'like' comments on posts. Is there a way for me to sort the comments based on the number of likes they have? Although I am aware of using .orderByChild(), my issue lies in not having a sep ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

What steps can be taken to turn this html code and css into a mobile application?

I have begun working on my HTML and CSS but need some guidance to create a mobile app without needing to resize it when accessed through the web. Additionally, I would like to make it responsive in CSS. Can you provide me with the necessary code? @c ...

I have a JavaScript code that smoothly scrolls to different id's on a webpage, but I need assistance in adding an exception for a particular id

I'm looking to incorporate smooth scrolling for all hash links in my JavaScript. However, I need the id=nav and its resulting hash link, /#nav, to be exempt from this functionality as it interferes with the menu responsiveness. Can someone provide gui ...

What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS. At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below: <ul ng-controller ...

Leveraging the 'clicked' variable in the Ajax success function

I am struggling to access a dynamic variable from the CSS class in an Ajax request. I have attempted the following without success. function watchlist($video_id, $user_id){ $.ajax({ url: "watchlist.php", data: {video_id : $video_id, u ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

What is the process for accessing an image via localhost on the same computer?

I created a program that saves images locally and stores their URLs in a database. When retrieving this data via ajax, the URLs are fetched and appended to a div class using the following code: $( document ).ready(function() { $.ajax({ url: "/ ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...

What is the best way to allocate a larger size to one part of a flex div?

A div is used to insert information <div class="inputs"> <div class="content">@Html.TextBoxFor(model => invoices.ProductDesc, new { disabled = "disabled", @readonly = "readonly" })</div> <div class="content">@Html.TextBo ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

The resource-intensive nature of ExpressJs HTTP Streaming is causing my disk space to deplete rapidly

My express server app.get('/data', (_, res) => { const interval = setInterval( () => res.write(`${Math.random().toString()}\n`), 1000 ); res.on('close', () => { clearInterval(interval); ...