javascript - How can I change the value that is connected to select change in dynamic form using jquery?
I was trying to make a form, which has two elements, one select item and one input price, select option are stored in database, so I retrieve it and display it.
User can add new row with same elements when button add is clicked, when the select option is changed, I am using ajax to get the price from database and displayed it in the text input.
It all worked fine with the first row but when user add new row I cannot retrieve the price and get the following message
"the specified value "NaN" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?"
How can I solve this problem or is there is another way to change the value of input using the row id
<table id="tab_logic">
<tr id='row0'>
<td>1</td>
<td>
<select name="item[]" required>
<?php
$items = "SELECT itemCode, itemName FROM items";
$itemslist = $conn->query($items);
while($row = $itemslist->fetch_assoc()) {
echo "<option value='" . $row["itemCode"] . "'>" . $row["itemName"]. "</option>" ;
}
?>
</select>
</td>
<td>
<input type="text" name='price[]' required/>
</td>
</tr>
<tr id='row1'></tr>
</table>
<button id="add_row" >Add Row</button>
<script>
function get_price(sel, item)
{
$.ajax({
type: "POST",
url : "getData.php",
data: {itemCode: sel },
success: function(data) {
$(item).find("input").val(data.price)
},
});
}
$(document).ready(function(){
//add new row when add buttomn clicked
var i = 1;
$("#add_row").click(function(){
var a = i-1;
$('#row' + i).html( $('#row' + a).html() )
.find('td:first-child')
.html(i+1);
$('#tab_logic').append('<tr id="row' + (i+1) + '"></tr>');
i++;
});
//when selected item change get parent and call function
$('#tab_logic select').on('change', function() {
var item = $(this).parent().parent();
get_price(this.value, item);
});
});
</script>
Answer
Solution:
I solved it finally, the problem was that get_price is only called one time on first change so I solved it using this way by calling the function onclick