I'm working on a class project to create a shopping list in jquery. I'm struggling with two similar issues.
As you can see from the image, I have an "Add" button and a remove "X" which both function a they should.
I'm trying to replace both of these objects with images I have created in Adobe Illustrator, the first a "plus +" icon and the second a "minus -" icon.
Any advice is much appreciated.
Shopping List
$(document).ready(function() {
$("#input-form").submit(function() {
var newItem = $("#input-item").val();
if (newItem.length > 0) {
var listItem = "<li>";
listItem += "<input type='checkbox'>";
listItem += "<span>" + newItem + "</span>";
listItem += "<span class='remove'>X</span>";
listItem += "</li>";
$("#items").append(listItem);
}
return false;
})
})
$(document).on("click", ".remove", function() {
$(this).parent().remove();
})
<body>
<div id="main">
<header>
<h1>Shopping List</h1>
</header>
<div id="input">
<form id="input-form">
<input id="input-item" type ="text">
<button type="submit">add</button>
</form>
</div>
<div id="list">
<ul id="items">
<!-- Items will go here -->
</ul>
</div>
</div>
</body>
I see you are using <button> tag for add and <span> for remove.
In any case, you can add image by:
<button type="submit"><img src="your/image/url"/></button>
<span class="remove"><img src="your/image/url"/></span>
Related
I have a problem concerning the use of .append("..."). I am coding a simple To-Do List and want to delete a list element when I click on the appended "REMOVE" button by reference to the buttons class.
I think it is not working because .append() isn't changing the html code of the website. At least I can't spot a difference after clicking the "ADD ITEM" button.
Do you have any ideas?
Thanks in advance!
var inputText;
var itemList = [];
$("#addButton").click(function(){
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
//not working
$(".deleteButton").click(function(e){
console.log("test");
var className = e.attr("id");
console.log("ID:" + className);
});
function showItems(){
$("#list").html('');
for(var i=0; i<=itemList.length-1; i++){
$("#list").append('<div class="listelement"><p type="text" class="listItem" id="listItem '+ i +'">'+ itemList[i] +'</p> <button type="button" class="deleteButton" id="'+ i +'">REMOVE</button><div>');
}
}
<body>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
You need to use event delegation.
$(document).on("click",".deleteButton",function(e) {
$(this).closest(".listelement").remove()
});
$(".deleteButton").click(function(e){ will only work on those elements that exist on the page, but not on newly added elements.
var inputText;
var itemList = [];
$("#addButton").click(function() {
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
//not working
$(document).on("click",".deleteButton",function(e) {
$(this).closest(".listelement").remove()
});
function showItems() {
$("#list").html('');
for (var i = 0; i <= itemList.length - 1; i++) {
$("#list").append('<div class="listelement"><p type="text" class="listItem" id="listItem ' + i + '">' + itemList[i] + '</p> <button type="button" class="deleteButton" id="' + i + '">REMOVE</button><div>');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
If you just want to remove that specific div where you are clicking you can use following code. You dont need to match id here.
$(document).on("click",".deleteButton",function(e){
let parent = $(this).closest(".listelement");
parent.remove();
});
But according to your code after delete if you add something, all the data of the array will show.Because you are not deleting data from array. I think you need to delete that data from the array too.
$(document).on("click",".deleteButton",function(e){
let parent = $(this).closest(".listelement");
let id = $(this).attr("id");
console.log(id);
itemList.splice(id, 1);
parent.remove();
});
The issue here is that the element appended doesn't have an event listener attached to it, when you're calling $(...).click it will attach an event listener only to the currently existing elements. Since you're calling it when the document loads and there are no elements with the class deleteButton at that time it won't do anything.
You can solve this by moving the deletion code to it's own function and attaching a click event listener for each new element you create.
In order to do so efficiently, you'll need to get the element you're creating, you can do this like so:
$(HTML Code).appendTo('#list').click(...);
This will create an element from the html you pass it, append it to the element with the id list and attach a click event listener to it, so in the end this will the result:
var inputText;
var itemList = [];
$("#addButton").click(function() {
inputText = $("#textInput").val();
itemList.push(inputText);
$("#textInput").val("");
showItems();
});
function deleteItem(e) {
console.log(e.target.id);
}
function showItems() {
$("#list").html('');
for (var i = 0; i <= itemList.length - 1; i++) {
var html = '<div class="listelement"><p type="text" class="listItem" id="listItem ' + i + '">' + itemList[i] + '</p> <button type="button" class="deleteButton" id="' + i + '">REMOVE</button><div>';
$(html).appendTo('#list').click(deleteItem);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="headline">
<h1 id="headline">TO DO LIST</h1>
</div>
<div class="userInput">
<input type="text" id="textInput">
<button type="button" id="addButton">ADD ITEM</button>
</div>
<div class="list" id="list">
<div class="listelement" id="listelement">
</div>
</div>
</div>
If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event only to the elements that exist at the time of binding
you can use
$(document).on("click", "button.deleteButton" , function() {
$(this).parent().remove();
});
https://jsfiddle.net/82d0e5at/3/
This code uses jQuery to "live" filter a li list:
<input id="filter_list" type="text" placeholder="Filter Playlist Tracks" />
Elsewhere on the page I have a list of images being called by a simple php/mySql query:
while($row = $result->fetch_assoc()) {
$img_url = $row['img_url'];
$img_name = $row['img_name'];
echo '<img src="'.$img_url.'"title="'.$img_name.'" onmouseoverHERE? />';
}
I need a JS mouseover in the image tag so that when I mouseover the image, the image NAME is dynamically placed in the INPUT filter_list text input element.
If possible, I need to input field to focus so that the list will be filtered using my existing jQuery. (NOTE: Currently it works fine if I manually enter text in the input field)
So I dont want it to simply popualte the text input -- it should both "populate" and "filter"
As a note, I dont care if we need an onClick or onMouseOver
Thank You - d
ACTUAL CODE
<!-- ***** SEARCH / FILTER INPUT ***** -->
<div style="border:0px solid #f00;margin:0px 0px 20px 0px;width:100%;padding:5px;">
<input type="text"
id='filter_playlist'
placeholder="Filter Playlist Tracks" />
</div>
echo '<table style="border:0px solid #f00">';
while($row = $result->fetch_assoc()) {
$album = $row['album'];
$album_pict = $row['source_poster'];
$count_row ++;
if($count_row == 1){
echo '<tr>';
}
echo '<td style="border:0px solid #f00;width:25%;padding:5px">
<img src="'.$album_pict.'" class="img-responsive"
data-toggle="tooltip"
data-container="body"
data-placement="bottom"
title="'.$album.'"
onmouseover="$(\'#filter_playlist\').value=\''.$album.'\';$(\'#filter_playlist\').focus();" />
</td>';
if($count_row == 4){
echo '</tr>';
$count_row = 0;
}
}
echo '</table>';
THIS IS THE JQ COD ETHAT HANDLES THE FILTERING
<!-- ----------------------------------- -->
<!-- ***** JS - FILTER PLAYLIST -->
<!-- ----------------------------------- -->
<script type='text/javascript'>
$(document).ready(function () {
(function ($) {
$('#filter_playlist').keyup(function () {
var rex = new RegExp($(this).val(), 'i');
$('.searchable li').hide();
$('.searchable li').filter(function () {
return rex.test($(this).text());
}).show();
})
}(jQuery));
});
</script>
OK IVE DISTILLED THIS DOWN TO THREE SIMPLE IMAGES USING STATIC CODE: CAN ANYONE HELP:
<html>
<head>
<!-- *JS* JQUERY ***** -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<!-- ***** SEARCH / FILTER INPUT ***** -->
<div style="border:1px solid #f00;width:33%;padding:5px">
<ul>
<li> Item 1</li>
<li> Item 2</li>
<li> Item 3</li>
<li> Item 4</li>
<li> Item 5</li>
<li> Item 6</li>
</div>
<div style="border:1px solid #f00;width:33%;padding:5px;">
<input type="text"
id="filter_playlist"
style="font-size:48px;
width:100%"
placeholder="Filter Tracks"
onkeyup="doFilterPlaylist()" />
</div>
<div style="border:1px solid #f00;width:33%;padding:5px;float:left">
<img src="http://www.underconsideration.com/brandnew/archives/google_2015_logo_detail.png" style="width:100px" title="Item 1"
onclick="document.getElementById('filter_playlist').value='Item 1';document.getElementById('filter_playlist').focus();doFilterPlaylist();" />
<br />
<img src="http://www.underconsideration.com/brandnew/archives/google_2015_logo_detail.png" style="width:100px" title="Item 2"
onclick="document.getElementById('filter_playlist').value='Item 2';document.getElementById('filter_playlist').focus();doFilterPlaylist();" />
<br />
<img src="http://www.underconsideration.com/brandnew/archives/google_2015_logo_detail.png" style="width:100px" title="Item 3"
onclick="document.getElementById('filter_playlist').value='Item 3';document.getElementById('filter_playlist').focus();doFilterPlaylist();" />
</div>
<!-- ***** JS - FILTER PLAYLIST -->
<script type='text/javascript'>
function doFilterPlaylist() {
var ele = $('#filter_playlist');
var rex = new RegExp(ele.val(), 'i');
$('.searchable li').hide();
$('.searchable li').filter(function () {
return rex.test(ele.text());
}).show();
}
</script>
</body>
</html>
When a user clicks on the first logo, the name should be placed in the text input box (This works), but it should also filter the list at top to only the item that matched (or includes the characters).
Hopefully this will make it simpler, staying away from all of the dynamic code. It will have to be transferred to dynamic code so simple "invisibles" or "hiddens" will not work.... Thank You in advance.
See test here http://www.musicpax.com/test.html
Give the images a shared class.
echo '<img src="'.$img_url.'"title="'.$img_name.'" class="playlistFilterImage" />';
Then try something like the following.
jQuery(function($){
var $filterList = $('#filterList');
$('.playlistFilterImage').on('mouseenter', function(e){
$filterList.val(e.target.title);
});
});
<input id="filterList" type="text" placeholder="Filter Playlist Tracks" />
Outline
You need to handle the mouseover event, so that when the user mouses over the image, the Javascript is called. Since there is not much code involved in focusing an element and changing its' value, you can do this inline.
Example code
<img src="something.png" onmouseover="$('#filter_playlist').value='name';$('#filter_playlist').focus();">
<input type="text"
id='filter_playlist'
placeholder="Filter Playlist Tracks" />
Explanation
onmouseover calls Javascript when a mouse over event occurs;
$('#filter_playlist') selects the element with the id filter_playlist using JQuery;
Setting filter_playlist's value to name enters the text name into the input box
Calling the focus() function on filter_playlist focuses it, to allow the user to easily edit.
Comment
As a usability note, I would use onclick over onmouseover. This is because the user may be moving their mouse trying to change tabs / apps / etc, and not necessarily be trying to interact with your site. To make this change, you simply need to replace onmouseover with onclick - it's that simple!
Activate Live Filtering
I have tested this on your site and it works. Replace the doFilterPlaylist() function with this:
function doFilterPlaylist() {
var val = document.getElementById("filter_playlist").value.toLowerCase();
var elements = $("#playlist li");
for (i=0;i<elements.length;i++) {
var txt = elements[i].innerText.toLowerCase();
if (txt.slice(0,1)==" ") {
txt = txt.slice(1);
};
if (txt.indexOf(val)===0) {
elements[i].style.display = "block";
}
else {
elements[i].style.display = "none";
};
};
};
Following code add div on click button. But I want to add classes to all divs in code with id(1), id(2) etc without clicking position. Is this possible.
JS:
$(function() {
$('button').on('click', function() {
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer").append('<div id="id' + ($sparkLines.length + 1) + '" class="sparkLines">Some Stuff Here</div>');
});
});
HTML:
<div id="sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
</div>
<button>Add Spark Line</button>
Actually I want to add class to all divs but with id1, id2, id3.
For example:
<div class="addclass" id="id1"></div>
<div class="addclass" id="id2"></div>
Hi you can do that using a counter on your function, Let me use Jquery on this.
function addDiv(){
var counter =0;
$('id').append('div id="' + counter +'"');
counter = counter + 1;
}
This should work.
Okay, once i see the answer to this, I will feel stupid. I'm certain of that.
I've created this exactly the way I want to before, but I am refactoring my code for a new version right now. I am trying to dynamically create collapsible sets in jQuery Mobile, but my html does not render right.
<div data-role="header">
<h2>Playground</h2>
</div>
<div data-role="content">
<div data-role="button" id="addprimary" data-inline="true">Add 5</div>
<div data-role="collapsible">
<h4>Collapsible</h4>
<form id="makecollapsible">
</form>
</div>
</div>
<div data-role="footer">
<h4>Please, no applause</h4>
</div>
</div>
<script>
$('#addprimary').on('click', function () {
Markup.Collapsible();
});
var Markup = new Object();
Markup.Collapsible = function () {
$('#makecollapsible')
.append($('<div>')
.attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
);
for (i = 0; i < 5; i++) {
($('<div>')
.attr({ 'data-role': 'collapsible', 'data-content-theme': 'c',
'data-collapsed': 'true' })
.html('<h4>' + i +'</h4>'))
.appendTo('#primary');
}
}
</script>
Could somebody please take a look at this http://jsfiddle.net/c2jLY/ and tell me what I have wrong? My <div>s with data-role='collapsible' are not rendering as collapsibles, which is also having an effect on the HTML I am trying to put in them later on.
Help is appreciated, thanks!
Inside Markup.Collapsible function and at the end of it, add the below. For collapsible-set, you need to tell jQM that you're enhancing a .collapsibleset() and combine it with .trigger('create').
$('#makecollapsible').collapsibleset().trigger('create');
Demo
I forgot to mention that when appending items dynamically, call enhancement methods on parent element; doing so, will enhance children elements. Thus, you don't need to use .collapsible().trigger('create') for each collapsible appended.
what i show here is a simple one but working:
<script type="text/javascript">
//dynamically make 10 collapsible items and append them to the collapsible-set
var jj = "SUPER item added..";
$('[data-role="content"]').append('<div id="set" data-role="collapsible-set"></div>');
var count;
for (count=0; count < 10; count++) { // div id should be from id='c0' to 'c9'
$("#set").append('<div id="c' + count + '" data-role="collapsible">');
$("#c" + count.toString()).append('<h3>Adding element_' + count +'</h3>');
$("#c" + count.toString()).append(jj + 'count ' + count + '</div>');
}
// either one is tested working below:
// $('[data-role="content"]').trigger('create');
$( "#set" ).collapsibleset( "refresh" );
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<!------------------------page 1 ListView template-->
<div data-role="page" id="page01">
<div data-role="header" data-theme="b" data-position="fixed">
<h2>-- DEMO -- </h2>
</div>
<div data-role="content" id="content">
</div>
</body>
I am using the jquery ui tabs to create dynamic tabs on the fly which will start off without any content. From what I can tell my code is building everything and putting it in the proper places, but jquery is not recognizing them as tabs. How would I get it to recognize the new tabs that were created after page load?
The html code:
<div class="main">
<div>
<button id="new">button</button>
</div>
<div id="tabs">
<ul>
<li>View1</li>
<li>View2</li>
<li id="createView">Create New</li>
</ul>
<div id="tabs-1">
<p>something on this page</p>
</div>
<div id="tabs-2">
<div>
<p>something else on this page</p>
</div>
</div>
</div>
</div>
the Javascript:
//Tabs functionality
$('#tabs').tabs();
//Create new view
var tabNum = 3;
$('#new').click(function() {
$('#tabs ul').append('<li>' + '' + 'newitem' + '' + '</li>');
$('#tabs').append('<div id="' + 'tabs-' + tabNum + '">' + '<div>new</div>' + '</div>');
var NewViewNum = 'tabs-' + tabNum;
$(NewViewNum).focus();
tabNum++;
});
The jQuery UI Tabs have a refresh method you can use per the documentation.
Try calling:
$("#tabs").tabs("refresh");