I am trying to pre-populate a list in a Bootstrap modal so that it can be selected from when the modal window is active. It is working to an extent, but when a selection is being made it's not being recognized. The click function is not firing. It works with other lists that are already populated.
HTML inside modal window:
<div class="btn-group"> <a class="btn btn-default dropdown-toggle
btn-select" data-toggle="dropdown" href="#">Country <span class="caret">
</span></a>
<ul class="dropdown-menu" name="listCountry" id="listCountry"></ul>
Click Function that is not firing on 'ListCountry':
$(".dropdown-menu li a").click(function(){
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText+'
<span class="caret"></span>');
});
Code that pre-populates the list:
$('#searchModal').on('show.bs.modal', function(e){
var countryList = $(e.currentTarget).find('#listCountry');
for (i = 0; i < gSearchObject.Countries.length; i++){
countryList.append("<li><a href='#'>" + gSearchObject.Countries[i]
['Country'] + "</a></li>");
}
})
The list looks fine but when I select an item the click function never gets fired. Have scoured many other answers but have not found anything quite like this one. Any assistance would be appreciated!
OK after MANY hours of tinkering I came up with a workaround that, although it works, I'm not happy about it. It seemed that the only way the click event would be fired is if the element itself was preexisting. So I created a large list of dummy entries, traversed through them and changed only the text, and then removed the extra entries at the end.
Here is the code:
$('#searchModal').on('show.bs.modal', function(e){
var countryList = $(e.currentTarget).find('ul#listCountry');
var el = $('#listCountry a:contains("Country")');
if (el.length > 0){
for (i = 0; i < el.length; i++){
if (i >= gSearchObject.Countries.length){
// must remove both a and li
el[i].parentNode.parentNode.removeChild(el[i].parentNode);
}
else
$(el[i]).text(gSearchObject.Countries[i]['Country']);
}
}
})
Although it works I hate the solution and would love to fix this kludge. Thanks.