I am fairly new to web-development, so please bear with me. So I have a for-loop that will dynamically generate options for a dropdown-menu using jQuery. I have an event listener specifically for buttons created dynamically and I simply want to retrieve the "value" attribute from the selected option. I'm not talking about .val, I'm talking about the 'value' attribute that I appended to the button during the for-loop process.
Some context: I am making ajax calls to the NewsApi (see: https://newsapi.org/) and I am populating the dropdown menu with options of online newspapers to choose from. The 'value' attribute is storing the 'id' key from the sources object that gets returned in the callback.
var sourceName;
var attr;
var title;
var description;
var url;
var source = 'engadget';
var queryURL = "https://newsapi.org/v1/articles?source="+source+"&apiKey=5d9f7c67d4384f35bd73aa91efca8a73";
var attr;
var title;
var description;
var url;
const length = 60;
///////////////////////////////////////////////////////////////////
//getting the sources from the api to
//be used in subsequent ajax calls
$.ajax({
url:"https://newsapi.org/v1/sources?language=en",
method: "GET"
}).done(function(response) {
console.log(response);
console.log(response.sources.length);
for(var i = 0; i < response.sources.length; i++){
console.log(response.sources[i].id);
console.log(response.sources[i].name);
console.log("======================");
// <a class="dropdown-item" href="#"></a>
// <a class="dropdown-item" href="#"></a>
// <a class="dropdown-item" href="#"></a>
source = response.sources[i].id;
sourceName = response.sources[i].name;
var newSource = $('<option>');
newSource.addClass('dropdown-item');
newSource.attr('name',i);
newSource.attr('href', '#');
newSource.attr('value', source );
newSource.text(sourceName);
$('.dropdown-menu').append(newSource);
}
});
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
$(document).on('click', 'option:selected', function(){
source = $('option:selected').text();
console.log('source: ' + source);
});
any help would be awesome