Reputation: 21
an application I have four dropdwon -menu where one of these is filled by selecting an earlier ... this is filled in automatically ... does not respond to click event
I have searching by answers about creating a dinamic UL LI itens and found this:
function getModelos(response)
{
var obj = JSON.parse(response);
try
{
var ul = document.getElementById("modelo");
var modelos = obj.modelos;
var x = document.getElementById("modelo");
while(x.length > 0)
{
x.remove(0);
}
for(i=0;i<modelos.length;i++)
{
var li = document.createElement("li");
var a = document.createElement("a");
a.appendChild(document.createTextNode(modelos[i].modelo));
a.setAttribute("href","#");
a.setAttribute("data-value",modelos[i].id+",.modelo");
li.appendChild(a);
ul.appendChild(li);
}
}
catch(err)
{
alert("ERRO: "+err);
}
}
also I have found a click event delegating:
$(".dropdown-menu li a").click(function()
{
var selText = $(this).text();
$(this).parents('.dropdown').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
var valor = $(this).data('value');
var options = valor.split(",");
$(this).parents(".dropdown").find(options[1]).val(options[0]);
if(options[1] == ".marca")
{
pedeModelos(selText);
}
});
all dropdowm-menus previously defined response to click on LI, but this dropdown dinamic created don't
I'm new to javascript/Bootstrap/JQuery, I need a way to follow, I will apreciate any help. thanks
Upvotes: 1
Views: 5869
Reputation: 8858
The issue is how you are delegating the click event. If your delegation is outside the event which is creating the dynamic elements than its not going to work. Your reference to the click event should happen in the same function where you are generating the dynamic html.
For example :
<input type="button" id="btn" value="GenerateHTML"/><br/>
<div>
</div>
$("#btn").click(function()
{
$("div").append("<ul class='dropdown-menu'><li><a href='#'>1</a></li><a href='#'>2</a></ul>");
$(".dropdown-menu").find("li a").click(function()
{
alert();
});
});
Upvotes: 0
Reputation: 22237
Like this:
$(".dropdown-menu").on("click","li a",function() {blah});
Read about Direct and delegated events
Upvotes: 1