remove this clicked list element with jQuery - javascript

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()
});

Related

How to add event listeners to the label of an input field on blur?

The input field is to contain a url. On blur, this event will update the input label's href,since this is a clickable label and should guide the user to a new page whose url has just been entered.
When the card containing this input is built, this function gets run. It adds event listeners to other pieces of the card, but this one doesn't seem to work.
function addEventListeners() {
const publishedPostInputs = document.querySelectorAll('.form-group.a input.published-link-input');
publishedPostInputs.forEach(input => {
input.addEventListener('blur', function() {
const link = this.value;
let plLabel = this.parentNode.parent;
plLabel.setAttribute('href', link);
});
});
}
<div class="col-12 mt-3">
<a href="https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg" target="_blank">
<label for="publishedPostLink">Published Link:</label>
</a>
<input type="text" class="form-control published-link-input" name="published-link" value="https://posts.gle/ZpUe9p">
</div>
<!-- IMAGES TO TRY:
https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg
https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg
-->
Issues with your code:
the querySelectorAll() did not match anything because .form-group.a does not exist, so remove it
addEventListeners() is not called, only defined
your <a> tag is not the parent, but a sibling, so go to parent and find the tag
Fixed code:
function addEventListeners() {
const publishedPostInputs = document.querySelectorAll('input.published-link-input');
publishedPostInputs.forEach(input => {
input.addEventListener('blur', function() {
const link = this.value;
const elem = this.parentNode.getElementsByTagName('a')[0];
elem.setAttribute('href', link);
});
});
}
addEventListeners();
<div class="col-12 mt-3">
<a href="https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg" target="_blank">
<label for="publishedPostLink">Published Link:</label>
</a>
<input type="text" class="form-control published-link-input" name="published-link" value="https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg">
</div>
<!-- IMAGES TO TRY:
https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg
https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg
-->
A better way to do it would be to listen for live change events from the input. That way if the value changes it will keep updating the link.
Note: I have edited the answer to better suit the needs, I did not understood the requirement was with multiple fields, this one works better.
Here is the code:
index.html
<!DOCTYPE html>
<html>
<body>
<div class="col-12 mt-3">
<a href="https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg" target="_blank">
<label for="publishedPostLink">Published Link:</label>
</a>
<input type="text" class="form-control published-link-input" name="published-link"
value="https://posts.gle/ZpUe9p">
</div>
<!-- IMAGES TO TRY:
https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg
https://images.pexels.com/photos/210019/pexels-photo-210019.jpeg
-->
<script src="./index.js"></script>
</body>
</html>
index.js
// Find inputs
const publishedPostInputs = document.querySelectorAll('input.published-link-input');
// Loop through inputs
publishedPostInputs.forEach(function (input) {
// Add event listener for input field change
input.addEventListener('change', function (e) {
// Get the link from the same parent element
const linkLabel = e.target.parentElement.querySelector('a');
// Set the attribute href to the value of the input field
linkLabel.setAttribute('href', e.target.value);
});
});

Jquery events not working with elements from append() [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Currently, I am creating something that will simply allow me to create tasks, click them when they are done and swipe left to get rid of them.
The problem I am having is that when the new tasks are appended, they are not affected by any of the JQuery events on in the script.
Tl;dr: appended divs are not affected by the below javascript, how can I fix this issue?
<div class="app">
<div class="appHeader">
<h2>Tasks</h2>
<form class="createTask">
<input type="text" class="createTaskInput" size="10" maxlength="25" placeholder="Type here to create your task..." //>
</form>
</div>
<div class="task">
<div class="summary">This is an example task
<br>When you complete a task, click the red button
<br>Should you want to remove a task, swipe left on the task.
</div>
<div class="completion"></div>
</div>
</div>
<script>
$(".completion").on({
'touchstart': function() {
$(this).addClass("completed")
}
});
$(document).ready(function() {
$("div.task").on("swipeleft", swipeleftHandler);
function swipeleftHandler(event) {
$(event.target).addClass("swipeleft");
}
});
$(document).ready(function() {
$(".createTask").submit(function(e) {
var value = $(".createTaskInput").val();
$('.app').append('<div class="task"><div class="summary">' +
value + '</div><div class="completion"></div></div>')
e.preventDefault();
});
});
</script>
That is because you add the event listener before you add the objects.
A workaround is to add the event listener to the body like this.
$( "body" ).on( "swipeleft", "div.task", swipeleftHandler );
and
$(" body ").on( "touchstart", ".completion", function(){
$(this).addClass("completed")
});
Because you are not binding them after you add a new task see below
function swipeleftHandler(event) {
$(event.target).addClass("swipeleft");
}
function touchHandler(event) {
$(event.target).addClass("completed");
}
$(document).ready(function() {
$(".completion").on('touchstart', touchHandler);
$("div.task").on("swipeleft", swipeleftHandler);
$(".createTask").submit(function(e) {
var value = $(".createTaskInput").val();
var totalExisting = $('div.task').length;
$('.app').append('<div class="task"><div class="summary">' + value + '</div><div class="completion"></div></div>');
var newTask = $('div.task').eq(totalExisting);
newTask
.on("swipeleft", swipeleftHandler)
.on('touchstart', touchHandler);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="app">
<div class="appHeader">
<h2>Tasks</h2>
<form class="createTask">
<input type="text" class="createTaskInput" size="10" maxlength="25" placeholder="Type here to create your task..." //>
</form>
</div>
<div class="task">
<div class="summary">This is an example task
<br>When you complete a task, click the red button
<br>Should you want to remove a task, swipe left on the task.
</div>
<div class="completion"></div>
</div>
</div>

How do I highlight/un-highlight div if checkbox is clicked OR it's parent div is clicked?

Right now when I click on li, it is highlighted correctly. However, when I click on the checkbox itself, there is no response. How do I highlight/un-highlight the li when clicking on either the li or the checkbox itself?
I also do not wish to adjust this part of my jQuery: $('.rightP').find('ul').on( (because the elements inside the ul are generated dynamically) if possible.
HTML
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
...
</li>
...
</ul>
...
</div>
JQuery :
deleteIDs = [];
$('.rightP').find('ul').on("click","li",function(event) {
var checkbox = $(this).find("input[type='checkbox']");
if(checkbox.hasClass('open')){
if(!checkbox.prop("checked") ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
}
});
I think if you want handle li click. You must not use check checkbox. You image and change it src to click.png when click and noclick.png when no click. Hope this help!
Ok if you dont want image i mention you my full code no use image, it work ok
<!DOCTYPE html >
<html >
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
</li>
</ul>
<script>
deleteIDs = [];
var isnotcheck=true;
var clickcheckbox=false;
$('.rightP').find('ul').on("click","input",function(event) {
clickcheckbox=true;
isnotcheck=!isnotcheck;
});
$('.rightP').find('ul').on("click","li",function(event) {
;
if(!clickcheckbox)
{
isnotcheck=!isnotcheck;
}
var checkbox = $(this).find("input[type='checkbox']");
clickcheckbox=false;
if(!isnotcheck ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
//alert(checkbox);
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
});
</script>
</div>
</body>
</html>
You look two event. li click and checkbox click , two event occured if you click on checkbox if no one event occured. You can see my variable
var isnotcheck=true;
var clickcheckbox=false;
to know click or not click checkbox.
Hope this help!
Rather than this line
$('.rightP').find('ul').on("click","li",function(event) {
You can try
$('.rightP').on("click","ul li",function(event) {
When you're dealing with generated content you should use deferred event handlers, here's an example using Jquery UI to apply the highlight effect when you click either the checkbox or div.
http://jsbin.com/kibicega/1/

html get div tag in many levels

I got class required on div tag, and I want to remove it change function of text field, but I can't get to that div level, please help me to reach this.parent.parent.closest('div')
<div class='required'>
<div>
<div>
<input type='text' value='123' onchange(removeRequired(this, this.parent.parent.closest('div')))/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(elm1, elm2){
if ($(elm1).val()) {
$(elm2).removeClass('required');
}
}
</script>
It seems that what you want is to add/remove the required class based on whether the input is empty or not.
$('.required').on('change', 'input', function(event) {
// add or remove required class
$(event.delegateTarget)
.toggleClass('required', this.value.length === 0);
});
It will work with the following HTML:
<div class='required'>
<div>
<div>
<input type='text' value='123'/>
</div>
</div>
</div>
It sets up event delegation on the outermost <div> elements and then sets or removes the required class based on the input value.
Demo
You dont have to mess up with javascript and jquery. You can bind the change event with jquery like this,
$(document).ready(function () {
$("input[type='text'] ").change(function () {
$(this).closest(".required").removeClass("required");
});
});
try this
$("input[type=text]").closest('div.required').removeClass("required");
onchange function be
$("input[type='text']").change(function(){
$(this).closest("div.required").removeClass("required");
});
or
$("input[type='text']").change(function(){
$(this).parents("div.required").removeClass("required");
});
Why not easily working with id?
<div id="input-wrapper" class='required'>
<div>
<div>
<input type='text' value='123' onchange="removeRequired(this, $('#input-wrapper'))"/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(elm1, elm2){
if ($(elm1).val()) {
$(elm2).removeClass('required');
}
}
</script>
By the way, if you want to reach the div class='required' with parent, you need 3 levels! Althougth the use of closest() is by far a better answer.
You can try:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<div class='required'>
<div>
<div>
<input type='text' value='123' onchange="removeRequired.call(this)"/>
</div>
</div>
</div>
<script type='text/javascript'>
function removeRequired(){
$(this).parent().parent().parent().removeClass('required');
}
</script>

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
});

Categories

Resources