Subho Subho - 6 months ago 11
Javascript Question

how to get the value of dynamically created selectbox

I am creating a div dynamically with ajax. Now if the ajax call is success then i created a string for div element and append it to the original div id.
here is my code

$.ajax({
type:"GET",
url:"resources/json/asnData.json",
dataType:"json",
success:function(data){
$.each(data.Payload, function(index, val){
i=i+1;
stmt+='<div class="row">'+
'<section class="col col-2">'+
'<label class="input"><i class="icon-append fa fa-key"></i>'+
'<input type="text" name="keyName" value="'+val.key+'" readonly/>'+
'</label>'+
'</section>'+
'<section class="col col-3">'+
'<label class="select">'+
'<select id="dataConversionType'+i+'" class="dataConversionType">'+
'<option value="HEX">HEX</option>'+
'<option value="ALL">Compare All</option>'+
'<option value="ASCII">ASCII</option>'+
'<option value="STRING">STRING</option>'+
'<option value="INT">INTEGER</option>'+
'<option value="BINT">BIG INTEGER</option>'+
'</select><i></i>'+
'</label>'+
'</section>'+
'<section class="col col-5">'+
'<label class="input"><i class="icon-append fa fa-dashcube "></i>'+
'<input id="convertedType'+i+'" type="text" value="'+val.value+'" readonly/>'+
'</label>'+
'</section>'+
'</div>';
});
$(".dataParser").append(stmt);


Now there is function where if someone select a value in selectbox then fire and show.

$('#dataConversionType'+i).change(function(e) {
e.preventDefault();
var conversionType=$(this).val(); //I have doubt here also..
console.log(conversionType);
if(conversionType == 'ALL') {
console.log('ALL-Show a modal with each possible conversion');
}


but this is not working. this function works if I called using the class name. But i have to call the function using id with the i value, so that with that i value i can also set some value in other fields.
any help will be appreciated...

anu anu
Answer

Use class instead of id (replace document with some non dynamic container)

 $(document).on('change','.dataConversionType',function(e) {
                e.preventDefault();
                var conversionType=$(this).val(); 
                console.log(conversionType);
                var index_val = $(this).attr('data-index')
                if(conversionType == 'ALL') {
                    console.log('ALL-Show a modal with each possible conversion');
                }
    )};

And when you are generating your element add a data attribute

'<select id="dataConversionType'+i+'" class="dataConversionType" data-index="'+i+'">'

Also if you are inside a loop you need to wrap your ajax within a closure if you want to get correct value and not the latest one.

(function(idx) {
  //ajax stuff here
}(i)