Jquery Remove Element from List - javascript

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

Related

JS: Fail to obtain object after change of filter

So I have a list of items with anchor a that successfully listen to the following event:
$('body[data-link="media"] #media_content a').on('click',function(e){
e.preventDefault();
var page = $('.page.active a')[0].innerHTML;
var date = $('.year_sorting .filter_years').val();
var id = $(e.currentTarget).data('media');
window.location.href = 'http://'+basePath+'media/content/'+id+'?date='+date+'&page='+page;
})
However in the same page, there is a filter allowing the user to change the year filter and once changed, the following execute and append a list of items that has the exact same layout as the a above $('body[data-link="media"] #media_content a'), which supposes to listen to the above event as well. the filter event is below:
$('.activity.filter_years').on('change',function(){
$('.pagination_ul').remove();
r_year = $(this).val();
$.get("media/getActivity",{type:'0',key:r_year}).done(function(d){
if(d.length>0){
$('#media_content').html('');
var ul = '<ul class="ap pagination-sm pagination_ul"></ul>';
$('.pagination_menu').append(ul);
for(var i=0;i<d.length;i++){
var p = ['',''];
if(!d[i].event_period){
p = ['style="color:#8A8A8A;"','style="color:#C7C7C7;"'];
}
if(locale=='en'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title+'</div></div></div>')
}else if(locale=='hk'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_zh+'</div></div></div>')
}else {
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_cn+'</div></div></div>')
}
$('#media_content').append(event);
}
pagination('.pagination_ul','.pagination-tr',Math.ceil(d.length/20),false);
}else{
$('#div_news_content_right').html('').append('<div class="not_available">No content available</div>');
}
})
})
in which you can see the list of items are being appended into the layout by JS. However, even with the same layout $('body[data-link="media"] #media_content a'), such appended list of items do not listen to the onclick event. the above js codes are together in a separate js file apart from the html file where I tried to put the first a event into the html file but the new appended list of items still do not listen.
Cannot think of other work around at the moment, please help to see what would be the cause of it. Thank you.
Maybe simple try this.
$(document).on('click', 'body[data-link="media"] #media_content a')
If your element is dynamic create you should bind the click event on document and target what's element should dispatch the event.This is different to bind click only on element because the event will unbind while you remove the element.
Updated:
I'm not sure I've understand all the script you have but I try to simplify the issue.
This is the jsbin and its work correctly.
JSBin

jQuery fade in on one <li>?

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.

How can I insert a div at the location where a user clicks inside a div?

Suppose I have a div that contains a sentence such as the one listed below:
<div class="sentence">This is a sentence</div>
I am trying to create a function/event handler that will recognize when the user clicks on the text inside the <div>. But, when they click inside the <div> the function needs to know exactly where they clicked so I can insert a <span> at that location. For example, if the user clicks in between the letters 'n' and 't' in the word 'sentence', then I want to insert a <span> there so I end up with
<div class="sentence">This is a sen<span>test</span>tence</div>
Something like this:
$('.sentence').on('click', function (e) {
var to_insert = '<span>test</span>';
// determine exactly where inside the div I clicked
// insert 'to_insert' at that location
});
Any ideas?
You can to get the position of the click in a string, using window.getSelection().anchorOffset
JS
$('.sentence').on('click', function (e) {
var to_insert = 'test';
var anchorOffset = window.getSelection().anchorOffset;
var resultHtml = $(this).html().substring(0, anchorOffset) + to_insert + $(this).html().substring(anchorOffset);
$(this).html(resultHtml);
});
DEMO

how to get text from nested span when li is clicked, with simple javascript

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;
// ...
}

Transform input back into a div on button click

I am using the following code
$(document).on('click', '#editDetailBtn', function () {
var input = $('<input id="#detailprimaryDescription" type="text" />');
input.val($('#detailprimaryDescription').text());
$('#detailprimaryDescription').replaceWith(input);
$('#editDetailBtn').hide();
$('#detailPrimaryCancel').show();
$('#detailPrimarySave').show();
});
$(document).on('click', '#detailPrimaryCancel', function () {
var input = $('<div id="#detailprimaryDescription" ></div>');
//input.val($('#detailprimaryDescription').text());
$('#detailprimaryDescription').replaceWith(input);
$('#editDetailBtn').show();
$('#detailPrimaryCancel').hide();
$('#detailPrimarySave').hide();
});
what I am trying to achieve is to once cancel is clicked then it will turne the input field back into a div
http://jsfiddle.net/7XWAu/
I think this is what you're shooting for.
JS FIDDLE
you don't need to place '#' at the beginning of an id in the dom, its only used to reference elements.
so basically, every where you had something like:
var input = $('<input id="#detailprimaryDescription_input" type="text" />');
you shouuld be doing something like:
var input = $('<input id="detailprimaryDescription_input" type="text" />');
once I cleaned that up it worked as it does in the fiddle.
I do want to say, that it would be a muchhhhhhh better practice to just show and hide a div containing all those inputs rather than manipulating the DOM to create / destroy them constantly.

Categories