user3284404 user3284404 - 3 years ago 74
HTML Question

JavaScript add new row and populate new rows inputs with data from dropdown value

I hope you can help me with a Javascript problem I'm having, I've been staring at this for days and I just can't figure it out!!

I've got a script that splits the value of an option dropdown and populates certain feilds with the splitted values.

Then I've got an 'Add Order Line' hyperlink to add a new row to a table, but I want the above feature to happen on any new line as well but nothing happens

I've recreated this in jsfiddle.

var selectEl = document.getElementById('part_selection');
selectEl.onchange = function () {
//var input1 = document.getElementsByName('PART_NO');
var input2 = document.getElementById('PART_DESCRIPTION');
var input3 = document.getElementById('PART_PRICE');
var input4 = document.getElementById('UNIT_MEAS');
var val = this.value;
var parts = val.split("_");
/*input1.value = parts[0];*/
input2.value = parts[1];
input3.value = parts[2];
input4.value = parts[3];
var counter = 1;

counter ++;

<table class="orderlinelist">
<td>Part Description</td>
<td>Unit Price</td>
<td>Line Total</td>
<tr >
<input type="text" name="ORDER_LINE_NO[]" class="ORDER_LINE_NO" id="ORDER_LINE_NO" value="1" readonly="readonly"/>
<select name="PART_NO" id="part_selection">
<option value="">Select a Part</option>
<option class="dropdown1" value="5461_Coxmoor Sideboard_299.00_EACH">5461</option>
<input type="text" name="part_desc" id="PART_DESCRIPTION" readonly />
<input type="text" name="PART_PRICE[]" id="PART_PRICE" class="orderprice"/>
<input type="text" name="QTY[]" id="QTY" class="orderqty"/>
<input type="text" name="UNIT_MEAS[]" id="UNIT_MEAS" class="orderuom"/>
<input type="text" name="TOTAL" id="TOTAL" class="orderprice"/>
<a href="#" title="" class="add-line">Add Line</a>

Can you point me in the right direction?


Answer Source

These are steps you can take to do what you want:

  1. first add class attributes to the input tags, instead of ID.

  2. Use jQuery .on() to handle your dynamic event.

  3. Use closest to find the current row.

  4. then using jQuery find, find the inputs based on their class attributes.

And continue the rest of your code scenario.

I took these steps on your code like:

$(document).on("change", "table.orderlinelist .part_selection", function () {
    var jrow = $(this).closest('tr');
    var input2 = jrow.find('.PART_DESCRIPTION');
    var input3 = jrow.find('.PART_PRICE');
    var input4 = jrow.find('.UNIT_MEAS');
    var val = this.value;
    var parts = val.split("_");

This is your working DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download