i have a row of inputs that are dynamically appended from a button. the first input is connected to a <datalist> that is populated by php from the database. when i click one of these items from the list, it pulls the price information for that specific item and i need it to automatically populate the next input with that price. i can alert("value.price"); just fine, but cannot think of a way to select only the corresponding <input>. if i use .class, it will select ALL of the dynamically generated inputs with that class and will change the price of all items to that price. obviously, i only want the one input in that one row to change. i am able to do that with my delete script by using closest but that is not applicable when it comes to the <input> within the row.
here is my script:
$(document).ready(function() {
$('#new_line_btn').click(function() {
$('#pricing').append('<div class = "row"><div class = "col-sm input_col"><input name = "part_input[]" class ="form-control part_class" list = "part_list"></div>'
'<div class = "col-sm"><div class = "input-group"><span class = "input-group-text">$</span><input class = "form-control price_class" name = "price[]" onchange = "this.value = Number (this.value).toFixed(2)"></div>'
'</div><div class = "col-sm"><div class = "input-group"><input class = "form-control"><button class = "btn btn-light btn-outline-secondary delete">x</button></div></div></div>');
});
$('#pricing').on("change", ":focus", function() {
var value = $(this).val();
var part_id = $('#part_list [value="' value '"]').data('id');
$.ajax({
url: 'invoice_array.php',
method: 'POST',
data: {
part_id: part_id
},
dataType: 'JSON',
success: function(data) {
alert(value.price);
}
})
});
$("#pricing").on("click", ".delete", function() {
$(this).closest("div[class = 'row']").remove();
});
});
as you can see i am appending a row with bootstrap columns and a delete button for that row. but how do i select ONLY the input with class = "price_class" and ONLY for that particular row?
this:
<input class = "form-control price_class" name = "price[]" onchange = "this.value = Number (this.value).toFixed(2)">
is where i need the price to appear.
the inputs are not direct siblings and the only other questions i see on similar topics are about .on() and selecting after dynamic element creation, which is not my problem.
in the code snip i have:
success: function(data){
alert(value.price);
}
but it should be something closer to:
success: function(data){
$('.price_class').val(value.price);
}
how do i select ONLY the price input for that dynamically created row? thank you
CodePudding user response:
Seems like you could access it in a similar way, just specify you want to target the last matching input.
$('#pricing').on("change", ":focus", function() {
let _this = $(this)
// ....
success: function(data) {
_this.closest('.row').find('input').last().val(data.price);
}
