Populate Input Field Based on Dropdown Selection

My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty.

Take a look at the outcome:

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

<td>
<select class="custom-select" id="kodeSparepart" name="kodeSparepart[]">
    <option value=""> --Select Sparepart-- </option>";
    @foreach($sparepart as $s) {
            <option value="{{ $s['kodeSparepart'] }}" data-price="{{ $s->hargaJual }}"> {{ $s['namaSparepart'] }} </option>";
     }
    @endforeach
 </select>
 </td> 
 <td> 
    <input class="form-control" type="text" id="hargaJualTransaksi" name="hargaJualTransaksi[]" autocomplete="off" readonly> 
 </td>

Additionally, here is the associated JavaScript:

// Insert new row into table
$(function(){
    $('#addMore').on('click', function() {
            var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
            data.find("input").val('');
    });

    $(document).on('click', '#remove', function() {
        var trIndex = $(this).closest("tr").index();
            if(trIndex>=1) {
            $(this).closest("tr").remove();
        } else {
            alert("Sorry! Unable to remove the first row!");
        }
    });
});    
// Populate hargaJualTransaksi field
$(function() {
    $('#kodeSparepart').on('change', function(){
        var price = $(this).children('option:selected').data('price');
        $('#hargaJualTransaksi').val(price);
    });
});

Answer №1

To ensure proper functionality when dynamically rendering rows to the DOM, event delegation is necessary:

$(function() {
    $('body').on('change', '.kodeSparepart', function(){
        var price = $(this).children('option:selected').data('price');
        $('.hargaJualTransaksi').val(price);
    });
});

IMPORTANT: The id attribute must be unique, so it is recommended to use classes instead of id's for each kodeSparepart and hargaJualTransaksi. For example:

<input class="form-control hargaJualTransaksi" type="text" name="hargaJualTransaksi[]" autocomplete="off" readonly> 

Answer №2

Check out the code snippet below:

$("body").on('click', '#kodeSparepart', function (event) {
  var price = $(this).children('option:selected').data('price');
        $('#hargaJualTransaksi').val(price);
}

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

An ultimate guide to mapping a nested array in React.js

Problem: I am struggling to display the entire content of my array. The goal is to render all elements in the array, but so far I can only get one to show up. I have found that including [key] in the object fields is the only way to generate any output. ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

What steps can be taken to receive an alternative result when selecting a checkbox?

Currently, I am tackling the issue with checkboxes in Vuetify. The challenge lies in achieving a different output for the second {{ selected.join() }}. For example, when I select the checkbox labeled "Social Media," I receive the text "On our social medi ...

Trouble obtaining output from chrome.tabs in browser console

Currently, I am experimenting with the browser's console and attempting to retrieve all the details of the active tabs. In order to do so, I open the browser's console and input the following: However, I encountered the following error: VM713:1 ...

Where should I place my custom menu script in Wordpress and how do I do it?

I am currently exploring the realms of PHP, Wordpress, and Javascript as I endeavor to transform my website, crafted with CSS and HTML, into a dynamic theme for Wordpress using PHP. One particular feature on my site is an off-screen menu that smoothly ope ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

Dynamic content in a CSS animation that rolls credits as they scroll

Currently, I'm working on creating a credit scrolling effect that pulls data from the JustGiving API to display a list of donors. I have successfully populated the list of donors and connected to the API without any issues. However, the challenge lies ...

Changing an AngularJS Protractor promise from a string to a decimal number - how to do it?

I am currently working with Angular.js Protractor to retrieve the values of cells in a grid. Although I can successfully retrieve these values, they are strings and I need to perform calculations with them. Upon attempting this: ptor.findElements(protrac ...

Is there a way to simulate a minified module for testing purposes?

For my project, I developed a component intended to function as a module. The implementation involves the utilization of third-party code provided in the form of a config file (initOpinionLab.js) and a .min.js file (opinionlab.min.js). As part of the devel ...

The resolution of the dynamic imported Vue component was not successful

Upon attempting to import a dynamic component using the import() function, I encountered the following error: [Vue warn]: Failed to resolve async component: function () { return __webpack_require__("./src/components/types lazy recursive ^\\. ...

How to retrieve only the last value from a JSON object using jQuery's .html

I'm having an issue with jQuery("#someID").html. It seems to only display the last name from the JSON data. Here is the javascript code: <div class="row" id="fetchmember"> <script type="text/javascript"> jQuery('#group').cha ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...

How can you fix the "bad value" response in mongodb when utilizing query parameters in the url?

{ "ok": 0, "code": 2, "codeName": "BadValue", "name": "MongoError" } Whenever I attempt to use query parameters skip and limit in the url, this error message pops up. localhost:5 ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

I am facing issues connecting my Express Node server to my MongoDB database using Mongoose

Starting my backend journey, I keep encountering the same error with my server.js --> // Step 1 - Create a folder named backend // Step 2 - Run npm init -y // Step 3 - Open in VS Code // Step 4 - Install express using npm i express // Step 5 - Create se ...

Set iframe or form to be in a fixed position

Having issues with my site where an iframe is contained within a div. When only one character is entered in the telephone box, validation fails and red warning text is displayed. Furthermore, after clicking in the email box and pressing tab twice, the fo ...

The issue of a non-firing Ajax click event in a JavaScript file

I have set up a table in JSP and am attempting to trigger a function when clicking on the table rows to post the data. I created a JavaScript file with an ajax click event, but unfortunately, the event is not being fired. $(document).ready(function( ...

Ways to connect a click event to a dynamically generated child element with the help of jQuery?

I am aware that similar questions have been asked elsewhere, but as someone new to jQuery, I am still struggling to attach a click listener to an a element within a dynamically appended ul.li.a structure in the DOM. Below is an example of how the structure ...

Utilize JavaScript to load images at random within a Qualtrics loop and merge block

I'm currently putting together a survey on qualtrics using a block with loop and merge functionality. I've encountered an issue where, after the first iteration, the images I'm loading through javascript start disappearing. Although I can br ...