Dynamically create <li> element on click - javascript

I have the following on html
<html>
<head>
<script src="../3003_Testing/js/jquery/dist/jquery.js"></script>
<script src="../3003_Testing/js/search.js"></script>
<title>Search Box</title>
<link href="mycss.css" rel="stylesheet">
</head>
<body>
<section class="main">
<form class="search" >
<input id="searchAddress" type="text" name="q" placeholder="Search address" oninput="getAddress()" />
<ul class="results" id="addressList">
<li id="staticli">Static li element<br><span>This is a Static li element</span></li>
</ul>
</form>
</section>
</body>
</html>
I am trying to get write a function to handle the event when any of the list element get clicked. But it doesn't seems to be triggering at all when I click on the <li> element.
$('#addressList').on('click', 'li', function() {
alert("clicked");
alert( $(this).text() );
});
The <li> elements are created dynamically through this code:
listContents = $("<li id=\"" + i + "\">" + addresses[i].lable + "</li>");
jQuery('#addressList').append(listContents);
And I verified through my browser's console that they are being created correctly as such
outerHTML: "<li id="0">6 Cashew Crescent<br><span>6 Cashew Crescent. (S)679751</span></li>"
Let's ignore about the dynamic list first. The thing is even my static list element are not responding to the event handler upon click. Have been trying to figure out the problem for a couple of hours now..
I have created a jsfiddle for my static li element not working https://jsfiddle.net/tmu50t9z/
jsfiddle to my whole code > https://jsfiddle.net/8wwnx64x/

$('#addressList li').on('click', function() {
alert("clicked");
alert( $(this).text() );
});

Work code, try this
HTML
<ul class="results" id='addressList'> </ul>
<button id="aaa">Add LI</button>
JavaScript
var a=0;
$('#aaa').click(function() {
$('#addressList').append('<li id="'+a+'">6 Cashew Crescent<br><span>6 Cashew Crescent. (S)679751</span></li>');
a++
});
$( "#addressList" ).on( "click", "li", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});

Related

remove this clicked list element with jQuery

I would really appreciate your help here. I want list item that is created with the "#save" button to be removed on click. The commented methods don't work. If i put 'h1' or something else it works no problem. Also the "#delBtn" button removes all list items no problem. But i cant;t make it work when i click on a list item to be removed. Thanks for your time in advance.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function(){
$("li").remove();
});
$("#save").click(function(){
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" +'First Name: '+ newContact.firstName + ' Last Name: '+ newContact.lastName + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
//---------------------------------------------------------------
// $("li").click(function() {
// $(this).remove();
// });
// $('li').click(function(e){
// $(e.target).remove();
// });
});
<!DOCTYPE html>
<html>
<head>
<link href="CSS/bootstrap.css" rel="stylesheet" type="text/css">
<link href="CSS/style.css" rel="stylesheet" type="text/css">
<script src="JS/jquery-3.2.1.js"></script>
<script src="JS/myjava.js"></script>
<title>Address book</title>
</head>
<body>
<div class="container">
<h1 id="haha" >Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact"><!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form><!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>
</body>
</html>
Try a delegated event listener. I believe that since these elements are being created dynamically, the event listeners don't find them and attach when the page loads. Try doing something like this:
`$(document).on('click', 'li', function () {
$(this).remove();
})`
What is happening is the document takes the event listener on page load and passes click effects to all li's after they are created.
This is most probably because you bind your click event on li elements that are already in your page at load time, and only at load time. This event won't apply for dynamically created new items…
Try this so answer.
If you want remove element li created by after document ready. You need use function delegate
Or you can write as below
$(document).on('click','li', function(){
var el = $(this);
el.remove();
});
This simple code should remove li items when clicked in the ul with id contacts.
$('#contacts').on('click', 'li', function (event) {
$(event.target).remove()
});

How to unwrap all li from ul on button click

This is probably a dummy question. I am trying to export the contents of a unordered list into a text area and remove the list item on export. I have achieved it at some degree but it only brings in the first list item.
How can I export all the li's?
HTML :
<div class="wrapper">
<button id="exportBtn">Export</button>
<div class="container">
<ul class="structure">
<li>Something</li>
<li>Something else</li>
</ul>
</div>
<div class="text">
<textarea id="exportTxt" contenteditable style=""></textarea>
</div>
</div>
This is my script :
$(function() {
$( "#exportBtn" ).click(function() {
var htmlString = $('.structure li').html();
$('textarea#exportTxt').html(htmlString).parent().is( 'li' ).htmlString.unwrap();
$('textarea#exportTxt').addClass('slideIn');
});
});
View working demo
So you want it to read SomethingSomething else.
$(function() {
$( "#exportBtn" ).click(function() {
var html = ''; // start with empty
$('.structure li').each(function(){
html += $(this).html(); // append the html from each li
$(this).remove(); // remove the li
});
$('#exportTxt').val(html); // set it in the textarea
});
});
Here is a jsfiddle with a working demo: http://jsfiddle.net/Grimbode/PucV2/
Hope this is what you wanted.
js:
$( "#exportBtn" ).on('click', function() {
$('.structure li').each(function(){
var txt = $('#exportTxt').text();
$('#exportTxt').empty();
$('#exportTxt').text(txt + ' ' + $(this).text());
$(this).remove();
});
});
html:
<ul class="structure">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<button id="exportBtn">Export</button>
<textarea id="exportTxt"></textarea>
Try this:
js
$("#exportBtn").click(function() {
var list="";
$(".structure").children().each(function(){
list +=$(this).html() + " ";
});
$('textarea#exportTxt').val(list);
});
fiddle

Jquery li click event not firing

I've been using JQuery and I tried my code on JFiddle and it worked fine but when I do it on my site it doesn't work at all, basically I need a event to be sent when a list item in my userlist is clicked.
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://dl.dropbox.com/s/r5pzakk4ikvck3t/style.css?dl=1">
<script src="https://www.dropbox.com/s/2hdvqa4ma51m0pw/jquery-1.9.0.min.js?dl=1"></script>
<title>Chat</title>
</head>
<body>
<div id="userlist-container">
<div id="userlist-title">User List</div><br />
</div>
<div id="main-container">
<div id="messages">
</div>
</div>
<div id="control-container">
<input type="text" id="TxtMessage" placeholder="Message" onKeyPress="SendMsg(event)" style="text-align:center;" >
</div>
<div id="alert-container" hidden="hidden">
<div id="alert-main">
<span id="alert-content"></span>
</div>
</div>
</body>
</html>
Javascript
$("#userlist-container > li").click(function(e) {
alert("TEST");
var username = "#" + this.html + " ";
$("TxtMessage").value(username);
$("TxtMessage").focus();
});
EDIT:
Once the page has loaded it connects to the server and adds <li>lalala</li> inside the userlist-container.
Your selector in the bind is wrong:
$("#userlist-container > li")
There is no li your HTML is:
<div id="userlist-container">
<div id="userlist-title">User List</div><br />
</div>
Also you seem to be missing # for the id selector inside the event.
So your event should probably be similar to:
$("#userlist-container > div").click(function(e) {
alert("TEST");
var username = "#" + this.html + " ";
$("#TxtMessage").value(username);
$("#TxtMessage").focus();
});
Edit
should have probably told you guys that once it does some wizzard
stuff, li's get added so there are actually li tags in there.
I added your code to a fiddle and no li tags seem to be added when inspecting the DOM.
The fiddle
That could be just the fiddle though, not sure. I'm assuming if the li tags are injected that you need to use delegate binding using on if you are using jquery 1.7 or later or delegate if you are using 1.6 or earlier.
Similar to this:
// jQuery 1.7 or later
$("#userlist-container").on("click", ">li", function(){
alert("TEST");
var username = "#" + this.html + " ";
$("#TxtMessage").value(username);
$("#TxtMessage").focus();
});
// jQuery 1.4.3 to 1.6.x
$("#userlist-container").delegate(">li", "click", function(){
alert("TEST");
var username = "#" + this.html + " ";
$("#TxtMessage").value(username);
$("#TxtMessage").focus();
});
Your selectors are wrong, add the # prefix to indicate an id
$("#TxtMessage").value(username);
$("#TxtMessage").focus();
If your click event isn't even firing, make sure that you are attaching the event after the document is loaded
$(document).ready(function(){
//code here
});

Jquery changing div text value upon clicking on li items

I am building a theme selector for maps and want to reflect the currently selected theme.
The code seems to work but never returns the value of the "li" item, it always returns "s-thumbs" for whatever "li" item I click on. I tried using the .closest() method but to no avail.
I'm following this article.
<script language="javascript">
$("ul.s-thumbs").live("click", function(event) {
$("#theme_title").text(
$(this).closest("ul.s-thumbs li").attr("class")
);
});
</script>
<div id="theme">You have selected the <div id="theme_title"></div> Theme</div>
<div class="container_16" id="themebg">
<!--<div class="grid_1"> <a href="" "img" src="/styles/image/leftarrow.png" id="leftarrow" alt=""/></div>-->
<div class="grid_16 slider-wrapper">
<ul class="s-thumbs">
<li class="Default"> <img src="/styles/image/thumbs/default.png" alt="" />Default</li>
<li class="Hatchery"> <img src="/styles/image/thumbs/hatchery.png" alt="" />Hatchery</li>
</ul>
</div>
$("ul.s-thumbs").on("click", "li", function() {
var myText = $(this).attr("class");
alert( myText );
$("#theme_title").text( myText );
});
Demo jsFiddle
Use the .on() metod: http://api.jquery.com/on/ adding the specific element after the event (click)
This is a new replacement for the (today) deprecated .live() method.
$('ul.s-thumbs li').on('click', function(){
var getClass = $(this).attr('class');
$("#theme_title").text(getClass);
});
Demo link: http://jsfiddle.net/ChaseWest/w2tCE/4/
$("ul.s-thumbs").on("click", "a", function(event) {
var txt = $(this).closest("ul.s-thumbs li").attr("class");
$("#theme_title").text(txt);
});
NOTE live() has been deprecated.
Add the event handler to the li instead of the ul. I also used on which is the preferred method in Jquery 1.7+
$("ul.s-thumbs li").on("click", function(event) {
$("#theme-title").html(
$(this).attr("class")
);
});
Demo: http://jsfiddle.net/euSye/1/
<script language="javascript">
$(document).ready(function() {
$(".s-thumbs").on("click", "a", function(e) {
$("#theme_title").text( $(e.target).parent("li").attr("class") );
});
});
</script>

jquery add li to end of ul but last created li not recognised as last

I have the following code. On cliking the button on the last li, I can create the new li. However, once created, if I click on the latest button created, new li is created. It seems it doesn`t recognise the last created li as the last li. Can someone help on this please.
<html xmlns="http://www.w3.org/1999/xhtml" >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mylist :button").click(function() {
var text = $(this).val();
if (text == "Save") {
}
});
$("#mylist li:last-child").click(function() {
$(this).parent().append('<li>' + '<input type = "textbox">' + '<input type = "button" value= "Save">' + '</li>');
});
});
</script>
<div>
<ul id="mylist">
<li id="1">1<button id="Button3">Delete</button> </li>
<li id="2">2<button id="Button2">Delete</button></li>
<li id="3">3<button id="another_entry">Save</button></li>
</ul>
<ul id="mylist2">
<li> test1 <button id="Button6">Delete</button></li>
<li> test2<button id="Button5">Delete</button> </li>
<li id="6"><button id="Button1">Delete</button></li>
</ul>
</div>
You need to use live instead of bind as bind iterates elements only once, however live creates a listener, which attaches events dynamically, even to newly created elements.
You code should conform to this sample:
$("#mylist li:last-child")
.live('click', function() {
// append element
});
tested with jQuery 1.4.0
Instead of:
$(this).parent().append('<li>'.........
Try
$("#mylist").append('<li>'.........

Categories

Resources