The issue of assigning Ajax data to jQuery inputs with identical classes is not being resolved correctly

I am currently developing an Invoicing System where the Rate(Amount) value changes automatically when the Product(Item) is changed.

The issue I am encountering is that when I change the first Product, all the other Product Rates change to the Rate of the first Item.

Below is the jQuery code snippet to change the Rate when a Product is selected:

//Values and Inputs
$(document).on('change', '.Item', function() {
    var Item = $('.Item').closest('.Item').val();
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
            $('.Rate').val(response);
        }
    });
});

Here is the code snippet for the Predefined Table:

<tbody class="TableBody">
  <tr>
    <td style="width: 220px">
      <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Product Name" required autocomplete="off">
    </td>
    <td>
      <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>
    </td>
    <td>
      <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>
    </td>
    <td>
      <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">
    </td>
    <td>
      <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>
    </td>
    <td>
      <button type="button" class="btn btn-danger DelRow">Delete</button>
    </td>
  </tr>

</tbody>

Below is the code snippet to Add a new Item:

$('#AddNewItem').click(function() { $('.TableBody').append(`
<tr>
  <td style="width: 220px">
    <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Product Name" required autocomplete="off">
  </td>
  <td>
    <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>
  </td>
  <td>
    <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>
  </td>
  <td>
    <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">
  </td>
  <td>
    <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>
  </td>
  <td>
    <button type="button" class="btn btn-danger DelRow">Delete</button>
  </td>
</tr>
`); });

Any assistance with this issue would be greatly appreciated.

Answer №1

Identify the specific input that belongs to the same row. This selection pertains to the initial input.

$(document).on('change', '.Item', function() {
    var item = this.value // access the updated item
    var row = $(this).closest("tr")  // obtain the table row associated with the item
    var rate = row.find(".rate") // locate the rate input within the row
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
          rate.val(response);
        }
    });
});

Answer №2

It appears that both your predefined table and dynamic table-row are using the same classes and id's. This means that if you use $('.Rate').val(response);, it will update all elements with the class ".Rate".

To avoid this, you can consider adding an incrementing number to differentiate the elements:

$('#AddNewItem').click(function() {

var i = parseInt($('.TableBody').length)+1; 

$('.TableBody').append('
.
.
<td>
    <input step="2" type="number" class="form-control text-right Rate_'+i+'" min="1" id="Rate" placeholder="0.00" readonly>
</td>
.
.
'); 

});

You have the flexibility to use different class names as well.

To access this number after an ajax call, you can add it as a data attribute to the ".Item" element:

$('#AddNewItem').click(function() {

var i = parseInt($('.TableBody').length)+1; 

$('.TableBody').append('
.
.
<td>
    <input type="text" data-loop="'+i+'" class="form-control Item" name="Item" id="Item" placeholder="Product Name" required autocomplete="off">
</td>
.
.
<td>
    <input step="2" type="number" class="form-control text-right Rate_'+i+'" min="1" id="Rate" placeholder="0.00" readonly>
</td>
.
.
'); 

});

For your ajax function, consider the following:

$(document).on('change', '.Item', function() {
var Item = $('.Item').closest('.Item').val();
var loop_id = $(this).data('loop');
$.ajax({
    type: 'GET',
    url: 'AjaxPrice.php',
    data: { Item: Item },
    success: function(response) {
        $('.Rate_'+loop_id).val(response);
    }
});

});

It may be necessary to pass the loop_id with the ajax call to access it in the success function. Additionally, consider using JSON as the dataType:

$(document).on('change', '.Item', function() {
var Item = $('.Item').closest('.Item').val();
var loop_id = $(this).data('loop');
$.ajax({
    type: 'GET',
    url: 'AjaxPrice.php',
    dataType: 'JSON', 
    data: { Item: Item, loop_id:loop_id },
    success: function(response) {
        $('.Rate_'+response.loop_id).val(response.html);
    }
});

});

These suggestions aim to provide some assistance.

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

Steps for organizing values based on the selected value from the dropdown menu in a select option

I have two drop down menus, defined as follows: <select name="" id="district" onchange="selectbyDistrict()"> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option&g ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

Merge different $_GET parameters together before submitting

Not too certain if it's achievable, but here's the issue I'm struggling with. I need a form that generates this specific link. The desired end link is: I am unable to utilize a form for this task, but I can work with input fields. Any sug ...

Arrange radio buttons vertically in a table

I am attempting to display a vertical list of radio buttons within a table cell. Is this achievable? Here is the code snippet I am currently working with: <table> <tr> <td> First Name </td> ...

Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like: var myArr = [ {&q ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

https://i.sstatic.net/yJmDY.jpg I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

Synchronizing jQuery parameters

I have developed a JavaScript shopping basket where the total sum updates automatically when a quantity is selected. However, I encountered an issue where the total value does not update when a product is removed unless the page is refreshed. Here's ...

Adding a scrollable feature to a Bootstrap Modal seems to be generating additional unnecessary pages at the

I need help with my scrollable bootstrap modal that has a print button on top. When the user clicks the button, I want to print the modal content. Here is the code snippet: HTML : <div class="container-fluid" id="body-noPrint"> /* HTML BODY CON ...

Utilizing CSS nested spans and setting custom width attributes

I'm curious about how nested spans and CSS handle the width attribute. In the HTML code provided, the 'wide' class sets the width while the 'box' class adds a border. I've noticed that the width is only applied when both class ...

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Error 400 occurs when attempting to make a PUT request on Firefox or IE, whereas it functions properly on Chrome and Opera

One particular website is utilizing jQuery to call a WCF Webservice on a different domain by making use of CORS. While most of the methods are GET requests, there are a couple of PUT requests as well. All the GET methods function properly across all brows ...

Delete the float attribute from the image when the inline-block is shifted to the bottom of the image

I have three elements in my design - a title, a paragraph, and an image. I want the image to float to the right, with the title and paragraph floating to the left and bottom, resembling "Image 1." To prevent the title from wrapping when narrowing the oute ...

Customizing the appearance of input range in Firefox

I am having trouble styling the HTML input range element. I have successfully styled it for webkit browsers, but my styling does not seem to work on -moz- browsers. I attempted to use pseudo elements before and after on moz-range-thumb, but it seems that F ...

Managing modules within the node_modules folder that have dependencies on .css files

Currently, I am involved in a project where we are utilizing a custom UI library that includes some dependencies. These components come with their own corresponding .css files. The structure of the source code looks like this: |- src |-| |- components ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

The functionality of a JQuery post within a PHP loop is not functioning optimally

I am encountering an issue with my list.php file, which generates a list with items and a button (Erledigt!) that triggers a jQuery Post to wishdelete2.php. The problem is that the jQuery post sometimes requires multiple clicks (3x or 5x) before it process ...

applying hover effect to text within a table

After investing some time into solving this issue, I am still struggling to find a solution. Essentially, what I want is for the :hover pseudo-class to trigger the border-bottom effect only when I hover over the text in a table. Currently, the :hover pseu ...

Altering the text of dropdown items prior to the ASP.NET autopostback

Recently, I inherited a project from a client that is plagued with some irritating issues. One particular problem involves a dropdown menu that triggers an autopostback event upon selection change, inserting the selected text into a T-SQL query. The troubl ...

Tips on retrieving specific information from PHP through jQuery AJAX

I have encountered an issue with my JavaScript file where I am sending an array of data to my PHP file. The problem is, when trying to print the name in #NAME and password in #PASSWORD, both values end up in both fields. You can see how it currently displa ...