问题描述:

i have DIV element in body and i copy that element to enable adding more elements to database but when i execute script that looks like this :

$(document).ready(function(){

$(document.body).on('change','.jobType',function(){

var value = this.options[this.selectedIndex].value;

select = this;

$.ajax({

url: 'getpart',

dataType: "json",

type: 'post',

data: {

part_id : value,

},

success: function( data ) {

wrapper = select.closest('.wrapper');

console.log(v, select);

inputPrice = wrapper.querySelector('.jobPrice')

console.log(inputPrice, data.Part.price);

inputPrice.value = data.Part.price;

}

});

});

});

var wrapper is null because is added to DOM dynamically, is there a way to use document.querySelector() on newly added element ?

网友答案:

I have added jquery statements to you existing code. If you have jQuery you can use it.

Changes:

1) var select = $(this);

2) var value = select.val();

3) var wrapper = select.closest('.wrapper');

4) var inputPrice = wrapper.find('.jobPrice')

$(document).ready(function(){

  $(document.body).on('change','.jobType',function(){
    var select = $(this);
    var value = select.val();
    $.ajax({
        url: 'getpart',
        dataType: "json",
        type: 'post',
        data: {
            part_id : value,
        },
        success: function( data ) {
            var wrapper = select.closest('.wrapper');
            console.log(select);
            var inputPrice = wrapper.find('.jobPrice')
            console.log(inputPrice, data.Part.price);
            inputPrice.val(data.Part.price);
        }
    });
  });
});
相关阅读:
Top