Nitish Nitish - 11 months ago 36
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>

I have a
add new
button which clone the div class

$('.add_more_item').click(function(e) {
var $item = $('.item');
var $clone = $item.clone(true).removeClass('item'); // Clone item

Now I want to update
field when the user changes the
. 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;

data : data,
url : url,
type : 'get',
dataType : 'json',

error : function(resp) {
success : function(resp) { console.log(resp.latest_rate);

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

Answer Source

In your code,

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

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

You should use


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();