Nitish Nitish - 3 months ago 10
jQuery Question

AJAX update for a input block in cloned div

I have a div structure as below :

<div id="items_block" class="col-xs-12" style="margin-bottom:15px;">
<div class="item material_item" style="border:1px solid #D9D6D6; padding:8px; background:#E7E3E3; margin:10px 0">
<div class="form-group ">
<label for="item_measurement_id" class="col-md-3 control-label">Item Measurement Id</label>
<div class="col-md-9">
<select class="required form-control col-md-12 item_measurement" id="item_measurement_id" autocomplete="off" required="true" name="item_measurement_id[]">
<option value="" selected="selected">Select Item</option>
<option value="1">pAPER</option><option value="2">KirloskarGREEN</option>
</select>
</div>
</div>
</div>


I have a
add new
button which clone the div class
material_item
:

$('.add_more_item').click(function(e) {
item++;
e.preventDefault();
var $item = $('.item');
var $clone = $item.clone(true).removeClass('item'); // Clone item
$clone.appendTo("#items_block");
show_hide_item(item);
});


Now I want to update
rate
field when the user changes the
item_measurement_id
. The AJAX is below :

$('.item_measurement').change(function(e) {

var url = '';
var data = '';
$this = $(this);
var item_measurement_id = $this.val();
$parent = $this.parent(); //$('.material_item');

url += '{{ route("rest.item_values") }}';
data += '&item_measurement_id='+item_measurement_id;

$.ajax({
data : data,
url : url,
type : 'get',
dataType : 'json',

error : function(resp) {
console.log(resp);
},
success : function(resp) { console.log(resp.latest_rate);
$parent.find('.rate').val(resp.latest_rate);
}
});
});


But I am getting anything in the rate field ! NB : I can see the correct value in console

Answer

In your code,

    $parent = $this.parent(); //$('.material_item');

is referencing the immediate parent, which is $('div.col-md-9')

You should use

$this.parents('.material_item') 

to access the element you're trying for.

Also, I would recommend instantiating $this and $parent using var to ensure they are scoped properly, like:

var $this = $(this);
var $parent = $this.parent();