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.
$(window).load(function(){
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];
}
});
$(function(){
var counter = 1;
$('a.add-line').on('click',function()
{
counter ++;
$(this).prev('table.orderlinelist').find('tr').last().clone().find('input').val('').end().find('input.ORDER_LINE_NO').val(counter).end().appendTo('table.orderlinelist');
});
});
<table class="orderlinelist">
<tr>
<td>Line</td>
<td>Part</td>
<td>Part Description</td>
<td>Unit Price</td>
<td>Qty</td>
<td>UoM</td>
<td>Line Total</td>
</tr>
<tr >
<td>
<input type="text" name="ORDER_LINE_NO[]" class="ORDER_LINE_NO" id="ORDER_LINE_NO" value="1" readonly="readonly"/>
</td>
<td>
<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>
</select>
</td>
<td>
<input type="text" name="part_desc" id="PART_DESCRIPTION" readonly />
</td>
<td>
<input type="text" name="PART_PRICE[]" id="PART_PRICE" class="orderprice"/>
</td>
<td>
<input type="text" name="QTY[]" id="QTY" class="orderqty"/>
</td>
<td>
<input type="text" name="UNIT_MEAS[]" id="UNIT_MEAS" class="orderuom"/>
</td>
<td>
<input type="text" name="TOTAL" id="TOTAL" class="orderprice"/>
</td>
</tr>
</table>
<a href="#" title="" class="add-line">Add Line</a>
These are steps you can take to do what you want:
first add class
attributes to the input
tags, instead of ID
.
Use jQuery .on() to handle your dynamic event.
Use closest
to find the current row.
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("_");
input2.val(parts[1]);
input3.val(parts[2]);
input4.val(parts[3]);
});
This is your working DEMO