I want to add elements on click event, there is an input text element and when user clicks on add I want to add that as an item to an unordered list. This is simple I prefer to do it with just JS but have to use JQuery. So, basically I want to:
get value of the input text
append li item to ul list
append a label for the li item
add value from input as text for label.
Here's my code - it's definitely not working but the above 4 steps is what I want to achieved in JQuery:
$(document).ready(function(){
var $add_button = $('#add-item')
var newItem;
var $incompleteTasks = $('#incomplete-tasks');
$add_button.click(function(){
newItem = $('#new-task').val();
// append new item to incomplete tasks ul
$incompleteTasks.append('<li>appended</li>')
.append('<label></label>').text(newItem);
});
});
With this one:
$incompleteTasks
.append('<li>appended</li>')
.append('<label></label>')
.text(newItem);
You're using a chaining. It means that every .append(something) returns $incompleteTasks element with updated content.
Calling .text(newItem) at the end, you're replacing whole content of the element by just single inputfield value:
$incompleteTasks
.append('<li>appended</li>')
//RESULT: <ul><li>appended</li></ul>
.append('<label></label>')
//RESULT: <ul><li>appended</li><label></label></ul>
.text(newItem);
//RESULT: <ul>newItem</ul>
If you want to append the value to the <label> and then that <label>...</label> to the <ul> element, you can do this way:
$incompleteTasks.append('<li><label>'+newItem+'</label></li>');
// OR:
$('<li><label>'+newItem+'</label></li>').appendTo($incompleteTasks);
// OR:
var label = $('<label/>').text(newItem);
$('<li />').append(label).appendTo($incompleteTasks);
// ...
You should end up with code like this:
$(document).ready(function(){
var $add_button = $('#add-item')
var newItem;
var $incompleteTasks = $('#incomplete-tasks');
$add_button.click(function(){
newItem = $('#new-task').val();
// Create <label> element and append text in:
var label = $('<label/>').text(newItem);
// Create <li> element, append prevously created <label>, and finally append that <li> to <ul>:
$('<li />').append(label).appendTo($incompleteTasks);
});
});
label{
display:block;
border: 1px solid #e0e0e0;
background:#fafafa;
width:200px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=new-task>
<button id=add-item>add-item</button>
<ul id=incomplete-tasks></ul>
Your problem in .text(newItem) because it is called on
$incompleteTasks and every time overrides ul's content.
Fix:
$incompleteTasks.append('<li>appended</li>').append('<label>'+newItem+'</label>');
http://jsfiddle.net/b4y8Lxf4/
Related
I am dynamically creating li with javascript, I want to add a close button to each li element created dynamically to delete the li element on click of the close button.This is my code so far:
function addNew(){
// get value from input field
var taskName = document.getElementById('task-name').value;
// innerHTML to be inserted inside li
var fullText = taskName + '<span class = "close" onclick =
"addListener(this)">×</span>';
// calling create function from Element object
Element.createNew('li','className','tasks',0,fullText);
}
// remove function
function addListener(e){
e.parentNode.parentNode.removeChild(e.parentNode);
}
The problem is the remove function removes the last li instead of li being clicked.
Here is the JSFiddle of the problem.
store all the list items in an array.
//suppose your list items have a class name 'lists'
//create a global var
var lis = document.getElementsByClassName('lists');
initially it'll be empty,
so in your add method(in which you're appending the new list item to ul,
push the new list item in the lists array.
and in the addEvent(e) method , loop around every element in the lists array
function addEvent(e){
for(var i=0; i<lists.length; i++){
if(lists[i] === e){
//remove the lists element by using lists[i] instead of e
// and remember to pop the lists[i] and resize the lists array
}
}
I'm creating a task manager app that creates a new li whenever the user adds an item. However, fadeIn() is triggering for every li on the page whenever a new item is created. Any help on getting fadeIn() to only fade in new items added?
$('form').submit(function() {
// Grab input and set it to lowercase
var input = $('.listInput').val().toLowerCase();
// Fade in li whenever an item is added
$('#list').append('<li>' + input + '</li>').hide().fadeIn(500);
// Remove text from input
$('.listInput').val('');
return false;
});
You can solve this by creating the element first, then appending it, and fading it in. I also prefer using css to make it initially hidden rather than jQuery hide():
$('form').submit(function() {
// Grab input and set it to lowercase
var input = $('.listInput').val().toLowerCase();
// Create new element first
var li = $('<li style="display:none">' + input + '</li>');
// Fade in li whenever an item is added
$('#list').append(li);
li.fadeIn(500);
// Remove text from input
$('.listInput').val('');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
<ul id="list">
<li>abc</li>
<li>def</li>
</ul>
<input type="text" class="listInput" />
<button type="submit">Submit</button>
</form>
$('<li>' + input + '</li>').hide().fadeIn(500).appendTo('#list'); will do. Fiddle.
I have a list in JQuery that's called additionalInfo, which is filled in using this JQuery function:
$('#append').on('click', function () {
//check if the following area is valid before moving on, check the jquery validation library
var text = $('#new-email').val();
var li = '<li>' + text + 'input type="hidden" name="additionalInfo" value="'+text+'"/> </li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
The point of the function is not only to store the info in a list that can be used later, but also to render a <li> with the info text in it. Right now I have another button on each <li> that when pressed, makes the li vanish, but I also need to add code to it that completely removes the info text from the additionalInfo list. This is the code I have for that method so far:
$('#removeEmail').on('click', 'li>.remove-btn', function (event){
$(event.currentTarget).closest('li').remove();
});
How can I get the segment of info text out of the li and then remove it from additionalInfo?
You have few problems. First of all when you create the new items, your markup is not correct. You were missing the opening bracket of input tag. Also i changed the code for delete so that it listens for the click event on any item with class remove-btn under the li element. This should delete the item when you click the remove link inside the li.
$(function(){
$('#append').on('click', function () {
var text = $('#new-email').val();
var li = '<li>' + text + '<input type="hidden" name="additionalInfo"
value="'+text+'"/>
<a href="#" class="remove-btn" >remove</a></li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
$(document).on('click', 'li>.remove-btn', function (event){
var _this =$(this);
_this.closest('li').remove();
});
});
Here is a working jsfiddle
I don't get jQuery yet, so javascript please. I need help adjusting my JS so it gets text from a nested span inside an li when clicked. i have it working now if you click the text, but id like it to work if you click the entire li without it getting the other nested elements (the image).
right now im working with the following html and js:
HTML:
<ul><li><img><span onclick="myfunction(this)">TEXT</span></li></ul>
<input id="iSupervisorUserName" name="OBKey_WF_Manger_Supervisor_1" type="text" />
JS:
function myfunction(span) {
var textInsideLi = span.innerHTML;
var field = document.getElementById("iSupervisorUserName");
field.value = textInsideLi;
I would like the text from SPAN to be written to the input when the li is clicked, not just the span. I know I should move the onClick call from the span to the li, but how do I adjust the JS so it get only the text inside the span and not the IMG as well?
here you go
html
<ul><li onclick="myfunction(this)"><img><span>TEXT</span></li></ul>
js
function myfunction(li){
document.getElementById("iSupervisorUserName").value=
li.getElementsByTagName('span')[0].textContent;
}
or
function myfunction(li){
document.getElementById("iSupervisorUserName").value=
li.childNodes[1].textContent;
}
anyway i would add an eventlistener to the ul or the li's.. as inline js is a mess if you wanna update the code later.also there is alot more code generated if you add onclick="myfunction(this)" on each li.
You may get the inner <span> element with .getElementsByTagName() method:
HTML:
<ul><li onclick="myfunction(this);"><img><span>TEXT</span></li></ul>
JavaScript:
function myfunction(li) {
var span = li.getElementsByTagName('span')[0],
textInsideLi = span.textContent || span.innerText,
field = document.getElementById('iSupervisorUserName');
field.value = textInsideLi;
// ...
}
I have to arrays that I have made. One grabs some anchor tags and the other a set of ul's. The anchor tags all have a name attribute and the ul's have id's that match the anchor tags name attribute. In addition to this, all the ul's have the class ".students" and ".hidden". (all the .hidden does is set the display:none)
<div>
<ul>
<li><h4><a name="5th-grade">5th Grade</a></h4></li>
<li><h4><a name="6th-grade">6th Grade</a></h4></li>
<li><h4><a name="7th-grade">7th Grade</a></h4></li>
<li><h4><a name="8th-grade">8th Grade</a></h4></li>
</ul>
</div>
<div>
<ul id="5th-grade" class="students hidden ">
<li>Billy Bob</li>
</ul>
<ul id="6th-grade" class="students hidden">
<li>Bob Sackamano</li>
</ul>
<ul id="7th-grade" class="students hidden">
<li>Matt Blunt</li>
</ul>
</div>
What I am trying to do is have it so when I click on one of the anchor tags, it will match it's corresponding name attribute to the ul with the same id, make it appear by removing the ".hidden" class, and then hide any other ul's that do not match by adding the ".hidden" class.
Here is what I have come up with so far using a little jquery and where I stopped:
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function(){
var i = '#' + $(this).attr('name');
$('.students'+i).removeClass('hidden');
for(var j=0;j<aStudents.length;j++)
{
console.log(aStudents.attr('id')[j]);
}
});
It's no problem getting the correct ul's to appear, but I couldn't add the ".hidden" class to the other ul's. I consoled it found that at least one of my problems is in the for loop, I am not going through each ul's in the aStudents array, but through the letters of the id of the first item in the aStudents array.
Am I even approaching this the right way? Have you got some ideas of how to do this?
Provided your html is valid (no duplicated IDs) this should do the trick.
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function() {
aStudents.addClass('hidden');
$('#' + $(this).attr('name')).removeClass('hidden');
});
jQuery iterates over the DOM elements out of the box when you call methods on it.
Also, if you want to know what was wrong with your initial loop, you should use [j] before retrieving the id attribute which is a string. So to retrieve the id property properly:
for(var j=0;j<aStudents.length;j++) {
console.log(aStudents[j].id);
}
$()[j] is a shorthand for $().get(j) (jQuery.fn.get docs).
Try this:
var aGradelist = $('#grade-list ul li a');
var aStudents = $('.students');
aGradelist.click(function(){
var i = '#' + $(this).attr('name');
aStudents.addClass('hidden');
$('ul' + i).removeClass('hidden');
}
What this does is add the hidden class to all the uls and then remove it only from that ul which has the id of the anchor that was clicked