How can we retrieve the key from a value and then multiply the price by the quantity?

Whenever I choose a category, the price is displayed in the select box. However, when I input a value in the quantity box, it multiplies the price and quantity to show the total. But instead of fetching the ID of the price and quantity multiplied from the ID, I want the multiplication of quantity and price directly. How can I achieve this?

Javascript for selecting price value from subcategories

<script src="{{ asset('js/jquery.min.js') }}"></script>
<script type="text/javascript">
    // Changing price..........
     $(document).ready(function() 
     {    
         $('select#subcategory').on('change', function() {
            if(subID = $(this).val()) 
            {
                $.ajax({
                        url: "{{url('/')}}" + '/Purchaser/add_purchaser/ajax/' + subID,
                        type: "GET",
                        dataType: "json",
                        success: function(data)
                        {
                            console.log(data);
                             $('select#productprice').empty();
                             $.each(data, function(key, value)
                             {
                                   var option = new Option(value, key);
                                   $(option).html(value);
                                   $('select#productprice').append(option);
                             });
                        }
                    });
            }else{
                $('select#productprice').empty();
            }
         });
    }); 
    </script>

Javascript for calculating total

<script type="text/javascript">
$('tbody').delegate('#price,#quantity','keyup',function(){
  var tr = $(this).parent().parent();
  var price = tr.find('#productprice').val();
  var quantity = tr.find('#quantity').val();
  var total = (price * quantity);
  tr.find('#total').val(total);
});
</script>

HTML file

<tbody>
   <tr>
      <td>
         <select class="form-control" name="cat_id[]" id="category">
             <option value="" disabled selected>Select Category</option>
                @foreach($category as $key)
                    <option value="{{ $key->id }}">{{ $key->cat_nm }}</option>
                @endforeach
         </select>
      </td>
      <td>
        <select class="form-control" id="subcategory" name="sub_cat_id[]">
          <option value="" disabled selected>Subcategory from category</option>
        </select>
     </td>
     <td>
       <select class="form-control" id="productprice" name="price_id[]">  
           <option>Price from subcategory</option>                                     
        </select>
     </td>
     <td>
        <input type="text" class="form-control" name="quantity[]" id="quantity">
      </td>
      <td>
         <input type="text" class="form-control" name="total[]" id="total">
       </td>
       <td>
          <a href="#" class="btn btn-danger" id="remove"><i class="fa fa-remove"></i></a>
        </td>
        </tr>
</tbody>

https://i.sstatic.net/96gii.png

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

Answer №1

Instead of using var price = tr.find('#productprice').val(); in the script below, it is recommended to use var price = $( "#productprice option:selected" ).text();:

 <script type="text/javascript">
      $('tbody').delegate('#price,#quantity','keyup',function(){
        var tr = $(this).parent().parent();
        var price = $( "#productprice option:selected" ).text();
        // var price = tr.find('#productprice').val();
        var quantity = tr.find('#quantity').val();
        var total = (price * quantity);
        tr.find('#total').val(total);
      });
</script>

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

Implementing jquery-confirm in CodeIgniter: A Step-by-Step Guide

I'm having some trouble with the jquery-confirm plugin from . Everything seems to be working fine, but when I try to delete an item, the jquery pops up an alert. However, when I click "okay", it doesn't actually delete the item. I can't figu ...

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

What is the best way to include multiple hostnames and pathnames in a Next.js configuration file for image assets?

My attempt to import multiple images from different hostnames for next/image is not working as expected. In my next.config.js, I have tried the following setup: module.exports = { images: { remotePatterns: [ { protocol: 'https&apos ...

Modify the parent variables within an HTML document

Attempting to update the var a within the hardcoded HTML page and then triggering an alert externally, but the value remains unchanged. This code is located in my content.js file. var a; function popUpWindow() { a="Nothing"; alert(a);// Shows "Not ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

Attempting to develop a kick command for discord using discord.js, which will initiate the kick action based on the user's

I've been trying to implement a discord kick command that specifically targets a user on my server. It may not be the most practical solution, but it's essential for my bot's functionality. Here's the code I have so far: if (command == ...

A computer program designed to determine a series of numbers needed to complete a square grid

Given the numbers 1, 2, 3, 4, 5, 6, 7, 8, I am seeking to replace the x's in such a way that each side adds up to the number in the center. *-*---*-* |x| x |x| *-*---*-* |x| 12|x| *-*---*-* |x| x |x| *-*---*-* Initially, I have iterated over the num ...

Working with AJAX in MonoDevelop

I've been spending a lot of time scouring the internet to figure out how to incorporate the AJAX toolkit in Mono ASP. From what I've learned, it seems like I need to add System.Web.Extensions to my list of references. However, I've encounter ...

In what way does React export a default function that invokes another function within the same file?

Within a JS file in React, I am exporting a default function to App.js. This exported function calls another function that was declared in the same file but was not explicitly exported. How does React know where to find this internal function? Does using e ...

Is there a way to disable text selection in AngularJS when double-clicking using ng-dblclick?

My element has ng-dblclick='doSomthing()' functionality that is functioning correctly, however, it also selects the text in the element which is not visually appealing. Is there a way to avoid this issue? ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

jQuery dynamically updating calculations on a single row consecutively

Currently, I am in the process of developing a small table to calculate potential winnings from betting on a rubber duck race with specific odds for each duck. I have managed to get most of it working but have encountered an issue... Upon loading the pag ...

Vuejs application experiencing pagination issues during development

I am encountering an issue while attempting to paginate an array within my vue.js app component. Upon building it, an error is displayed in the vue ui output console: warning Replace `·class="page-item"·v-for="(item,·index)·in·onlineCa ...

"My PHP headers are not working properly when I try to

When I invoke a script with JavaScript var user = document.getElementById('username').value; var pass = document.getElementById('password').value; var conf = document.getElementById('confirm').value; var code ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

Using jQuery to determine the value and dynamically stay on the current page

Is there a way to ensure that the page stays the same if the login (data.login != 1) is incorrect? I attempted using preventDefault, but it doesn't seem to be effective. Can someone offer assistance? $(document).on('submit', '#login&ap ...