Subho Subho - 1 year ago 74
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

$.each(data.Payload, function(index, val){
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/>'+
'<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>'+
'<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/>'+

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

$('#dataConversionType'+i).change(function(e) {
var conversionType=$(this).val(); //I have doubt here also..
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 Source

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

 $(document).on('change','.dataConversionType',function(e) {
                var conversionType=$(this).val(); 
                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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download