Getting value of dynamically generated dropdown Jquery

Today I got stuck in a peculiar issue. It looked pretty basic to me but somehow I have spent more than 2 hours on it and its still not resolved.

I have a dropdown which I am generating dynamically.
jQuery Version – v1.11.1

$.ajax({
	        url: 'digitalImpactHeaders',
	          success: function(data) {
	            $(document).ready(function(){
	            	countryChannelObj = data;
	            	populateImpactCountry("US");
	            	populateImpactHeader("US");
	            });
	          }
	        });


//Response Structure 
/*
{
    "US": [
        "Display",
        "Paid Social"
    ],
    "DE": [
        "Non-IM Mktg Initiatives",
        "Paid Social",
        "Programmatic",
        "Display"
    ],
    "UK": [
        "Programmatic",
        "Paid Social",
        "Display",
        "Non-IM Mktg Initiatives"
    ]
}
*/

function populateImpactCountry(defaultCountry){
	$.each(countryChannelObj, function(index){
		$("#impactCountry").append($("<option />").val(index).text(index));
	});
	$('#impactCountry option[value="'+defaultCountry+'"]').attr("selected",true);
}

function populateImpactHeader(country){
	$("#impactChannel").html("");
	var channelData = countryChannelObj[country];
	if(channelData.length >0){
		$("#impactChannel").append($("<option />").val("All").text("All"));
	}
	$.each(channelData, function(index) {
		$("#impactChannel").append($("<option/>").val(channelData[index]).text(channelData[index]));
	});
}
<select id="impactCountry" name="impactCountry"></select>

<select  id="impactChannel" name="impactChannel" ></select>

With the code provided I am able to populate the dropdowns with dynamic values.
Now, I want to get the selected value of this dropdown after the page loads for the first time (There is no change event happening. Right after page load). Whenever I do

var country = $('#impactCountry option:selected').val(); //undefined
var channel = $("#impactChannel option:selected").val(); //undefined
    			

var country = $('#impactCountry').val();  //null
var channel = $("#impactChannel").val();  //null

I am not sure what I am missing here. One thing that I can think of is that since the options are dynamically introduced to the page the browser is not able to register these pages and hence when I do a .val() it does not know if these nodes even exist.

I tried searching for similar post but couldnt find it. Any help is appreciated.

Thanks,
Vatsal Pande


Source: jquery

Leave a Reply