javascript click event on dropdown menu - javascript

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

Like this:
$(".dropdown-menu").on("click","li a",function() {blah});
Read about Direct and delegated events

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();
});
});
http://jsfiddle.net/pkhout3x/

Related

How to rebind an event listener to elements that are removed and added again

I have built a pretty complex slider and now have to build it so it can be removed and re-added to the page based on a selection. I have a simple click event listener for the pagination to call all my animations and timers that looks like this
let $slideItems = $slideShow.querySelector('.slideshow-items'),
$slideshowNav = $slideShow.querySelector('.slideshow-nav'),
$slideshowNavButton = $slideshowNav.getElementsByTagName('button');
forEach($slideshowNavButton, (index, el) => {
el.addEventListener('click', function() {
let isActive = this.classList.contains('active');
if (!isActive) {
clearTimeout(timer);
slideshowClick($slideShow, this);
slideshowAnimations($slideShow, index);
slideTimer();
}
});
});
I use the forEach function as a for loop to go through all the elements I need, like having multiple $slideShow's on the page, and return them as an indexed array. The issue I am having is that I need to add a functionality in which the $slideshowNav and all the $slideshowNavButtons get removed and rebuilt from a function outside of the $slideshow function and can't figure out how to rebind the click event without repeating all of the code. Is there a way to bind this event to the $slideshow object, similar to the way jQuery's .on function works or rebind the click event to the new $slideshowNavButton's after they are created? I am not able to use jQuery so I can't use the .on function.
its hard to give you correct answer since you motion too many classes without visual placement but hope this helps:
var btnWraper = document.querySelectorAll('.btnWraper > button');
btnWraper.forEach(function(e){
e.onclick = buttonClicking;;
})
let remake = document.getElementById('reMakeMe');
remake.addEventListener('click', function(){
var btnWraper = document.querySelectorAll('.btnWraper > button');
//if deleted
if(!btnWraper.length)
{
createButtons('Btn1');
createButtons('Btn2');
createButtons('Btn3');
createButtons('Btn4');
}
},false)
let rest = document.getElementById('resetMe');
rest.addEventListener('click', function(){
var btnWraper = document.querySelectorAll('.btnWraper > button');
btnWraper.forEach(function(e){
e.remove();
})
},false) ;
function buttonClicking (){
alert(this.innerHTML);
}
function createButtons(value){
var btn = document.createElement("button");
btn.innerHTML = value;
btn.onclick = buttonClicking;
var parentElement = document.getElementsByClassName("btnWraper")[0];
parentElement.appendChild(btn);
}
<div class="btnWraper">
<button>Btn1</button>
<button>Btn2</button>
<button>Btn3</button>
<button>Btn4</button>
</div>
<div>
<button id="resetMe">Reset All</button>
<button id="reMakeMe">ReMake All</button>
</div>

Pass element as argument when creating event via DOM - JS Javascript

I'm trying to create HTML elements usingn DOM. I need to pass the <li> element to the toogle method as follows:
<ul>
<li onclick="toogle(this)"><a>Some text</a></li>
</ul>
How can I do it?
Current code that doesn't work:
var li = document.createElement("li");
li.onclick = toogle(this);
var li = document.createElement("li");
li.onclick = function () { toogle(this); };
This:
li.onclick = toogle(this);
actually EXECUTES that toogle function, and assigns its return value to the onclick. If you want your function to be called AS the click handler, then it should be
li.onclick = toogle;
The Snippet below demonstrates how to pass an element that was clicked by using event.target. Details are commented in source.
SNIPPET
var li = document.createElement("li");
// Needs to be in DOM before you can click it
document.querySelector('ul').appendChild(li);
// Assigning class for testing
li.className = 'klass';
// Add click event for li
li.addEventListener('click', function(e) {
// event.target is always the element that was clicked
var tgt = e.target;
// Verifying that the li was passed
console.log(tgt.className);
// klass
}, false);
li {
background: #000;
}
<ul></ul>
You can do:
var li = document.createElement("li");
li.addEventListener('click', toogle);
Which will call toogle on click. This is the better way to do it.
and then you can get the element with:
function toogle(e) {
// "e.target" will represent the element
}
Or if you want it your way then you can do:
var li = document.createElement("li");
li.onclick = toogle;
and then you get the element with:
function toogle() {
// "this" will represent the element
}

Appending an element to a cloned element

I have a form with an HTML table that has a button (#addRows) that when clicked will clone the first table row and append it to the bottom of the table.
This table resides in a section of HTML with some other input fields that can also be cloned and appended onto the bottom of my form. When I am cloning the section I am changing all child element ID's to include a number that can be iterated dependent on how many times the user clones the section.
Example
<div id="someID"> ... </div>
<div id="someID2"> ... </div>
<div id="someID3"> ... </div>
I am doing this with JQuery like this
$(function() {
var $section = $("#facility_section_info").clone();
var $cloneID = 1;
$( ".addSection" ).click(function() {
var $sectionClone = $section.clone(true).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + $cloneID); });
$('#facility_section_info').append($sectionClone);
$cloneID++;
});
});
When I clone the section that holds the table I am also cloning the #addRows button which when clicked should append a table row to the table it is being clicked on. However if I clone my section and I click on my second `#addRows button it will clone my table row but it is appending to my first table and not the second.
Here is my addRows button and event handler
<input type="button" value="+" id="addRows" class="addRows"/>
$(function() {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone();
$idVal = 1;
$(document).on('click', '.addRows', function(){
var copy = $firstTRCopy.clone(true);
var newId = 'row' +$idVal;
copy.attr('id', newId);
$idVal += 1;
copy.children('td').last().append("Remove");
$componentTB.append(copy);
});
});
My question is, when I clone my section of HTML that holds my table and #addButton how can I ensure that when the user clicks on the original button it will clone and append to that table or if I click the cloned button it will clone and append to the cloned table only?
If anything is unclear please let me know so I can try to better explain what I am trying to do, thanks.
Here is a JSFiddle demonstrating the problem I am having.
Because I truly love you BigRabbit, here is where I got to. You will see at least one useful fix here:
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
and a fix for an issue you did not report yet
$copy.children('td').last().append(' Remove');
using
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
FIDDLE
$(function () {
var $componentTB = $("#component_tb"),
$firstTRCopy = $("#row0").clone(),
$section = $("#facility_section_info>fieldset").clone(),
$cloneID = 0,
$idVal = 0;
$("#facility_section_info").on('click', '.remove', function (e) {
e.preventDefault();
$("#"+$(this).data("removeid")).remove();
});
$("#facility_section_info").on('click', '.addRows', function () {
$idVal++;
var $copy = $firstTRCopy.clone(true);
var newId = 'row' + $idVal;
$copy.attr('id', newId);
$copy.children('td').last().append(' Remove');
$(this).closest("fieldset").find("tbody").append($copy);
});
$("#facility_section_info").on("click", ".addSection", function () {
$cloneID++;
var $sectionClone = $section.clone(true);
$sectionClone.find("*[id]").andSelf().each(function () {
$(this).attr("id", $(this).attr("id") + $cloneID);
});
$('#facility_section_info').append($sectionClone);
});
});

How can I trigger onblur from a ul li?

I am essentially highlighting each li when clicked, and want to "un-highlight" the clicked li when clicking elsewhere or tabbing out (by effecting the background-color property).
This behavior would essentially be emulating <select> in its' highlighting behavior... I'm not using select though, because I want to nest HTML inside the listed items  --  you can't do this with <option>.
I'm attempting to use onblur, which is not working...
Here is the HTML:
<ul id = "list">
<li>asdf</li>
<li>qwerty</li>
<ul>
...here is the CSS:
#list {
list-style-type: none;
}
...and here is the jQuery/Javascript:
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
function highlightSelection(selection) {
alert("It worked!");
$(selection).css("background-color","#FFFF00");
}
// this function is not being triggered:
function removeHighlight(selection) {
$(selection).css("background-color","none");
}
var ul = document.getElementById("list");
ul.onclick = function(event) {
var target = getEventTarget(event);
highlightSelection(target);
};
// this event is not working:
ul.onblur = function(event) {
var target = getEventTarget(event);
removeHighlight(target);
};
The lis don't blur because they don't focus. Try with mouseout or mouseleave.
Since you're already using JQuery...
<ul id = "list">
<li tabindex="1">asdf</li>
<li tabindex="2">qwerty</li>
<ul>
var ul = $("#list");
ul.on('click focus','li',function(){
$(this)
.css("background-color","#FFFF00")
.siblings().css('background','');
}).on('blur','li',function(){
$(this).css('background','');
});
http://jsfiddle.net/mc4tN/2/
I wasn't sure of what effect you wanted when you tab away from a list item... It seems you would just want to leave it highlighted. You can add focus-ability to your list items by giving them a tabindex attribute.

Jquery dynamic dropdown event not firing

Hi i am trying to create dropdownlists dynamically and populating the contents via an ajax call, this sort of works in the sense that the drop down is created and populated as required but its 'change' event does not fire. I am posting the code below, if anyone can spot something obvious, can you please let me know
regards
$(document).ready(function () {
$("#positions select").change(function (e) {
alert("in");
var id = $("#category_id").val();
$.getJSON("/Category/GetSubCategories/" + id, function (data) {
if (data.length > 0) {
alert(data.length);
var position = document.getElementById('positions');
var tr = position.insertRow(7);
var td1 = tr.insertCell(-1);
var td = tr.insertCell(-1);
var sel = document.createElement("select");
sel.name = 'sel';
sel.id = 'sel';
sel.setAttribute('class', 'category');
td.appendChild(sel);
$.each(data, function (GetSubCatergories, category) {
$('#sel').append($("<option></option>").
attr("value", category.category_id).
text(category.name));
});
}
});
});
});
If your drop down is dynamically generated then you have to bind the change event using .live() handler. live() attaches a handler to the event for all elements which match the current selector, now or in the future.
$("positions select").live("change", function(){
});
Edit
To get the id
$(this).attr("id");
To get value
$(this).val();
To get class name
$(this).attr("class");
inside the change event handler.

Categories

Resources