Get li value from ul filled by JavaScript [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have filled some "ul"s directly in HTML e.g.
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
<span class="caret"></span></button>
<ul class="dropdown-menu" id="measure">
<li>volume</li>
<li>netSentiment</li>
<li>authors</li>
</ul>
and had no trouble reading the selected value by
$('#measure li').on('click', function(){
$(this).text();
});
Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:
Something like
$('#projectId').append('<li>' + projects[i].name + '</li>');
The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

When you dynamically add new elements after the page has loaded, you need to delegate the events to a parent element. You've almost done this, just change you code to
$('#measure').on('click','li', function(){
$(this).text();
});
Note your method here will not do anything - but ive kept the code as close to your example. Perhaps you meant console.log($(this).text());

What you need is Binding for dynamically created elements
$('#measure').on('click', 'li', function(){
alert($(this).text());
});
$('#measure').append('<li>abc</li>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="caret"></span></button>
<ul class="dropdown-menu" id="measure">
<li>volume</li>
<li>netSentiment</li>
<li>authors</li>
</ul>
Here i have created abc li using jquery but still on clicking it, it gives alert just like other li.

Related

Add event listener to every row in a dynamic table?

I have a table that I am populating using a JSON file. The amount of JSON entries, and therefore table rows, can be any length. Each row contains a bootstrap dropdown button that has links used for things like renaming or deleting the table row.
I've tried several solutions I found online, most including a foreach loop, but I had lots of issues trying to implement those into my code.
function populate()
{
$.getJSON(, {})
.done(function(data) {
$.each(data, function(i, items)
{
table.append(
`<tr>
<td>
<div class="btn-group dropdown">
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Actions
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#" onclick="renameEntry()">Rename</a>
</div>
</div>
</td>
</tr>`
)
});
});
}
As you can see, I've tried using an onclick() method to trigger a js function, but I don't know how to best differentiate between rows so the onclick() only affects the relevant row.
Any help is greatly appreciated.
using an onclick() method to trigger a js function
Is usually frowned upon because you're mixing presentation with logic. Makes it difficult to debug.
If you're dynamically adding anything to the DOM and want click events occuring against these dynamic elements, JQuery provides a way to target them without performance penalty of bubbling event handlers, nor any dynamic adding of listeners as you add elements.
You can use the .on() method to target elements in a container.
$(document).ready(() => {
$('.js-add-row').on('click', () => {
$('.js-dyn-table').append('<tr><td>New Row <button class="js-hello">Hello</button> </td></tr>')
});
// Target the first container that has dynamic elements,
// in this case the table
// the second selector is the element that we want the event to occur on: .js-hello
$('.js-dyn-table').on('click', '.js-hello', (e) => {
// e.currentTarget is the element the event occured on
var $btn = $(e.currentTarget);
// closest will work it's way up parent html elements until it finds the first match
var $tr = $btn.closest('tr');
$tr.toggleClass('bg-yellow');
});
});
table{
border: 1px solid green;
margin-top: 10px
}
.bg-yellow {
background-color: Gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="js-add-row" type="button" value="Add Row">
<table class="js-dyn-table">
<tr><td>Existing Row<button class="js-hello">Hello</button> </td></tr>
</table>
You just need an element in this case this that will allow you to access the DOM element that has been clicked, that you will get back to the level with the e (you can give any name).
I do not know what you intend to do with this information, but in my example, I explain how to access the DOM element that was clicked.
Look at the code below, and I hope it will help you.
function test(e) {
e.style.background = "red";
}
<div onclick="test(this)">
<button>Click me</button>
</div>

Asp.net bootstrap dropdown menu - selecting an item

I have an ASP.net project which used Bootstrap controls. I have the following Bootstrap dropdown menu which pulls in the list items programmatically from a database.
However, when i click on the menu and select one of the items, i obviously need that item to show in the dropdown box. Instead, when an item is clicked, nothing happens apart from the dropdown menu is closed.
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" id="merchantList" data-toggle="dropdown" aria-expanded="false"> Choose Merchant <span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="merchantList" id="myList" runat="server">
<asp:Literal runat="server" id="merchantDropDown"></asp:Literal>
</ul>
</div>
I'm assuming some kind of JavaScript is needed to set the dropdown menu to whichever item has been selected. But i'm not sure how to do it.
I've tried:
$("#myList li a").click(function () {
alert('clicked');
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText + ' <span class="caret"></span>');
});
also tried:
$('#myList li a').on('click', function () {
$('#merchantList').val($(this).text());
});
But these never seems to get called. Any ideas? It would be even better if I could do this in the code behind as I prefer to work back there.
Correct me if I am misunderstanding what you are looking to do but shouldn't you be able to find the item that they selected and set its css class="active". To figure out that the current item they selected matches the current page they are on there are several techniques using the URL.
Try doing something like the following on your master page:
var url = window.location;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
I did it like this in the end and it seems to all be working. Simple enough i just couldn't figure it out as i'm a JS newbie!
<script>
$().ready(function () {
$('a').click(function () {
var value = $(this).text();
$('#merchantList').html(value + ' <span class="caret"></span>');
alert(value);
});
});
</script>

JQuery fadeOut only works on first element [duplicate]

This question already has answers here:
jQuery click function only works on first element
(8 answers)
Closed 8 years ago.
I have a div containing other div elements which all contain an anchor tag that runs a javascrip function (uses AJAX to delete a row from a table). Example;
<div id="container">
<div><a id="btn" onclick="SomeFunction()">Delete</a></div>
<div><a id="btn" onclick="SomeFunction()">Delete</a></div>
<div><a id="btn" onclick="SomeFunction()">Delete</a></div>
... and so on
</div>
I then have this Jquery code;
$("#btn").click(function() {
$(this).parent("div").fadeOut();
});
that should fade out each of the elements on click to my knowledge, but it's only fading out the first element, if i click the next elements button's nothing happens.
I don't have extensive JQuery knowledge to understand why this is happening.
Ids must be unique, use classes instead.
Ids
[...] elements can only have one single ID defined through the id attribute. Note that an element may have several IDs, but the others should be set by another means, such as via a script interfacing with the DOM interface of the element.
classes
Classes allows CSS and Javascript to select and access specific elements via the class selectors or functions like the DOM method
Reference
Example
HTML:
<div id="container">
<div><a class="btn" onclick="SomeFunction()">Delete</a></div>
<div><a class="btn" onclick="SomeFunction()">Delete</a></div>
<div><a class="btn" onclick="SomeFunction()">Delete</a></div>
</div>
jQuery:
$(".btn").click(function() // Identify classes by a dot and the class attribute value.
{
$(this).parent("div").fadeOut();
});
Working Demo
Offtopic: I recommend taking a look at .on().
You can only have one element on a page with the same id. jQuery is getting confused. Use class or attribute selectors instead.

My JS selector for <ul> is not working [duplicate]

This question already has answers here:
Attaching click event to a JQuery object not yet added to the DOM [duplicate]
(10 answers)
Closed 8 years ago.
I'm using multiple Bootstrap dropdown controls and need to set a value to an input field when a list item of a specific dropdown is selected. For example, say I have 3 dropdowns:
ulSaukContact
ulMoselContact
ulShipContact
All three are running on the server, and I need to get the value of each so I can save them somewhere. So I figured I should probably save the value of each to a hidden input field that I can reference later. Here is my attempted JS code for doing this:
$("#ulSaukContact li a").on("click", function () {
alert('sauk'); // <--- Alert is not shown
var elem = document.getElementById("inpSaukValue");
elem.Value = $(this).text();
});
and the accompanying markup
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" id="btnSaukList" data-toggle="dropdown" runat="server"
style="width: 100%;">
<span style="padding-right: 250px;">Select a Saukville contact</span>
<span class="caret"></span>
</button>
<ul id="ulSaukContact" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" runat="server" style="width: 100%">
<!--NOTE: Intentionally left blank; li's are generated by code behind to populate users from Sharepoint.-->
</ul>
<input id="inpSaukValue" type="hidden" />
</div>
When I run the app and select a value in the Saukville dropdown, no alert is displayed. Note that the li's and a's within the ul is created on Form_Load so they can be populated with data. I think my selector is wrong. I cleared out my cached files in Chrome (which caused issues before) and I still do not see the alert.
Any advice appreciated (thanks for all the recent JS/BS/JQ advice)...
Because the elements don't exist at the time you're attempting to bind events to them, you need to delegate events to the containing element with on:
$("#ulSaukContact").on("click", "li a", function () {
...

Using .click instead of onclick and getting a variable value

I have seen that the inline/html events like onclick, mouseover etc are being used less and less and it is advised to register events using Javascript.
I currently have some HTML like:
<ul id="supported-locations">
<li onclick="setLocationId(32);">Mexico</li>
<li onclick="setLocationId(35);">Mongolia</li>
</ul>
Which works fine but I want to now do this without the "onclick" in the HTML but still be able to retrieve the ID number.
The <li> elements are retrieved via AJAX while the user types into an input box it queries the database and retrieve the data without loading the page.
When the user clicks on one of the countries it will run the setLocationId function which just simply sets a hidden HTML form element with the ID of the selected country so I can use that once the form is submitted.
How do you register an event listener for these <li>'s when the countries and their ID's will always be different and changing depending on what the user types into the box?
Use a data attribute to hold the number. On the onclick event, read the attribute on the element that was clicked.
HTML:
<ul id="supported-locations">
<li data-code="32">Mexico</li>
<li data-code="35">Mongolia</li>
</ul>
JavaScript:
$("#supported-locations").on("click", "li", function() {
var li = $(this);
console.log(li.data("code"));
});
Example:
JSFiddle
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
in jQuery
$('#supported-locations').on('click','li',function(){
setLocationId($(this).data('id'));
})
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
jQuery(function(){
$('#supported-locations li').click(function(){
alert($(this).data('id'))
})
})
I recommend giving a class to the dynamically loaded elements, then use jquery .on(http://api.jquery.com/on/) method to register event listeneres to elements belonging to a class, even those that are dinamically loaded..
Then you could just read out the data stored in the element(in the form of data-something attributes).
<ul id="supported-locations>
<li id="32">Mexico</li>
<li id="35">Mongolia</li>
</ul>
//Jquery
$("#supported-locations > li").on('click',function(){
setLocationId($(this).attr('id'));
});
When you register your event, you still have the ability to use this, which is linked to the HTML element.
In other word, you still can do something like that
<li id="YOUR_ID">Mexico</li>
And get the id of the li tag
You can attach an event handler to the li:
<ul id="supported-locations">
<li id="location32">Mexico</li>
<li id="location35">Mongolia</li>
</ul>
$("#supported-locations li").click(function() {
alert($(this).attr("id"));
});
http://jsfiddle.net/puL95/
try this.
$("#supported-locations li").click(function() {
alert("me")
}

Categories

Resources