Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list:

<select id="itemsList" onchange="gettingList()">
    <option>Please choose an option</option>
    <option value="50">Shampoo</option>
    <option value="100">Toothpaste</option>
    <option value="290">Lotion</option>
</select>
<br><br>

My objective is to retrieve the price of the selected product from the list. However, I am facing challenges in obtaining the result after clicking the button.

<input type="number" id="price" disabled="">
<br><br>

<input type="number" id="quantity" onChange="calculate()">
<br><br>

<input type="number" id="result">


<button type="button" onclick="addDetails()">Add</button>

In addition, I have included code for displaying the data in a table format.

<table id="myTable" border="1">
  <tr>
    <th>Product Name</th>
    <th>Price</th>
    <th>Quantity</th>
    <th>Amount</th>
  </tr>
</table>
<br>

Although I have implemented a script to handle this functionality, I am encountering issues in achieving the desired outcome.

<script>
    

    
var getPrice = document.getElementById('itemsList');

function getList () {
    document.getElementById('price').value = getPrice.value;
}


function calculate () {
    var prc = document.getElementById('price').value;
    var qty = document.getElementById('quantity').value;
    var result = prc * qty;
    document.getElementById('bill').value = result;
}



function addDetails () {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1. = document.getElementById('itemsList').value;
    cell2. = document.getElementById('price').value;
    cell3. = document.getElementById('quantity').value;
    cell4. = document.getElementById('bill').value;
}

</script>

Is there a better way to populate the cells of the table with the necessary details?

Answer №1

The proper way to achieve this:

const 
  formElement = document.querySelector('#my-form')
, tableElement = document.querySelector('#my-table tbody')
  ;
formElement.oninput = event =>
  {
  if (formElement.product.value!=='0')
    {
    formElement.price.value = formElement.product.value
    formElement.bill.value  = formElement.price.valueAsNumber * formElement.quantity.valueAsNumber 
    }
  else
    {
    formElement.price.value = ''
    formElement.bill.value  = ''
    }
  }
  
formElement.onsubmit = event =>
  {
  event.preventDefault() // preventing the default submit action

  if (formElement.product.value!=='0')
    {
    let row = tableElement.insertRow()
    row.insertCell().textContent =  formElement.product.selectedOptions[0].textContent 
    row.insertCell().textContent =  formElement.price.value 
    row.insertCell().textContent =  formElement.quantity.value
    row.insertCell().textContent =  formElement.bill.value

    formElement.product.value  = '0'
    formElement.price.value    = ''
    formElement.quantity.value = '1'
    formElement.bill.value     = ''
    }
  }
* {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 14px;
}
label {
  display : block;
  margin  : .5em 0;
}
label span {
  font-size : .9em;
  display   : block;
}
input {
  padding-left: .7em;
}
table  {
  border-collapse : collapse;
  margin          : 2em 1em;
  }
thead { 
  background-color : lightsteelblue;
  font-weight      : bold;
  }
th, td {
  padding    : .2em .8em;
  border     : 1px solid darkblue;
  }
td {
  text-align: right;
  }
td:nth-of-type(1){
  text-align: left;
  }
td:nth-of-type(2)::after,
td:nth-of-type(4)::after {
  content : ' \20a8';
  }
<form id="my-form">
  <label>
    <span>Product :</span>
    <select id="product">
      <option value="0" selected disabled>Select an option</option>
      <option value="50" > Soap  </option>
      <option value="100"> Sugar </option>
      <option value="290"> Oil   </option>
    </select>
  </label>
  <label>
    <span>Price :</span>
    <input type="number" name="price" disabled>
  </label>
  <label>
    <span>Quantity</span>
    <input type="number" name="quantity" value="1" min="1">
  </label>
  <label>
    <span>Amount</span>
    <input type="number" name="bill" disabled>
  </label>
 
  <button type="submit">Add</button>
</form>

<table id="my-table">
  <thead>
    <tr> <th>Product Name</th> <th>Price</th> <th>Quantity</th> <th>Amount</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

Vue Websockets twofold

I am experiencing some issues with Laravel/Echo websockets and Vue.js integration. I have set up everything as required, and it works, but not quite as expected. The problem arises when I refresh the page and send a request - it displays fine. However, if ...

Append a constant string to the conclusion of the route parameter

Using React Router v6.4.1, I am aiming for a consistent conclusion to a series of dynamic routes. Specifically, I want my product detail routes to always end with "-product". For example, if the path is "/shaver-900-product", it should activate my Produc ...

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

What is the best method for creating an HTML table using a Javascript function in PHP?

When working with a PHP file to generate a table based on SQL query results, I encountered an issue where only one incorrect row is returned. If anyone has a basic idea of what might be happening, it would be greatly appreciated. This is my HTML Code: &l ...

Tips for switching the irregular polygon shape image on click and hoverIf you want to change

I'm looking to create a unique menu with an irregular shape in Adobe Illustrator. I've attempted the following code: <div class="body_container"> <img src="img/sitio_Web.png" alt="" usemap="#sitio_Web_Map" height="787" bor ...

Performing an AJAX GET request to the API after a set time interval

The API is constantly updating with live values, so I am attempting to fetch the data every second and display it on the webpage. Although I used a GET request call every N seconds using set_interval(), the values only load once and do not update with eac ...

Tips for breaking out of the foundation row and aligning with the right edge of the viewport

I have a CodePen example showcasing the Zurb Foundation grid. I am looking for a way to make a div extend to the right edge of the viewport while keeping the left edge in line with the grid as the viewport is resized. <div class="row"> <div cla ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" https://i.sstatic.net/5dLJ ...

nyroModal automatically adapts its dimensions according to the size of the webpage, not the size of

A situation has arisen with a link that opens an image using nyroModal. While everything is functioning correctly, the Modal window appears in the center of the page instead of aligning with the middle of the browser window. As a result, only the upper por ...

Consistently maintaining a uniform distance between icons and the border box is essential

I am working on a team overview for a company where data such as name, job title, and information are fetched from the database. Due to varying lengths of information, the icons are not aligning properly in one line. https://i.sstatic.net/cEmKj.png Does ...

AngularJS Resource GET Request Unsuccessful

Is there a way to verify if a resource failed to be fetched in AngularJS? For instance: //this is valid syntax $scope.word = Word.get({ id : $routeParams.id },function() { //this is valid, but won't be triggered if the HTTP response is 404 or an ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Django informing me that the template is not found

Why am I getting a "template does not exist" error in Django? I'm trying to navigate from film_detail.html to film_report.html by clicking on the "report" button... views.py class FilmReport(LoginRequiredMixin, UpdateView): model = Report fi ...

When you hover over a Wordpress page, the entire text on the page will be underlined

Currently designing my own website using WordPress with the Elementor free plugin and Phlox theme. I've made some progress by completing a few sections which include text, buttons, and images. However, I'm encountering an issue where all the text ...

Issue with ng-model causing incorrect variable binding

My issue lies with a variable that I have connected to a select input through the use of ng-model. Strangely, the variable seems to not update with the correct data and retains the value assigned to it during initialization. I have a similar setup elsewhe ...

How can I add rows to the tbody of a table that is already inside a div container?

I have an existing table and I want to append a tbody element to it. Below is an example of the HTML table: <div id="myDiv"> <table class="myTable"> <thead> <tr> <th>ID</th> ...

Can a person select a characteristic like "height" using Javascript?

Is it doable to set a height for an image in CSS, then detect this gradient using JS and double the width based on the height x2.25? Could this be achieved? ...

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...