Removing div's appended using jQuery append() - javascript

Hi i have a button which add's a div to my html using jquery append(). Now each of the div's appended has a close button which removes the appended div using jquery remove(). The code looks like this:
$(document).ready(function(){
$("#image-btn").click(function(){
var $imageElement = $("<div class='image_element' id='image-element'><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' id='close-img-btn' width='22px'><button type='button' class='img_btn' id='img-btn'>Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
$("#close-img-btn").click(function(){
$imageElement.remove();
});
});
});
Now the problem is arises while removing the appended div's. When i add multiple div's (Each has a close button) and click on the close button of the last appended div nothing happens. But clicking on the close button of the first appended div closes all the other appended div.
I am trying to close only the div that i hit close and not the others. How do i do this ? Would really appreciate if someone could guide me through. Thanks.

ID of an element must be unique, when you use id selector it will return only the first element with the id, so all the click handlers are added to the first button.
Use classes and event delegation
$(document).ready(function () {
$("#image-btn").click(function () {
var $imageElement = $("<div class='image_element' ><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' width='22px'><button type='button' class='img_btn' >Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
});
$("#element-holder").on('click', '.closebtn', function(){
$(this).closest('.image_element').remove();
})
});
Demo: Fiddle
More Read:
Event binding on dynamically created elements?

You need remove the parent/child near at button you press.
For example:
$("#close-img-btn").click(function(){
$(this).parent('content-div').remove();
});

use $(this) instead of $imageElement
$(document).ready(function(){
$("#image-btn").click(function(){
var $imageElement = $("<div class='image_element' id='image-element'><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' id='close-img-btn' width='22px'><button type='button' class='img_btn' id='img-btn'>Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
$("#close-img-btn").click(function(){
$(this).remove();
});
});
});

Related

Insert html icon within a div with .before method

In this case,
I have some div like:
<div class="topImg">
<div class="topImgIcon">
<img src="img/bbbbb.png" class="topImgIcon"><span class="tittle">Chat Window</span>
</div>
</div>
And I want to insert this img link with one icon within this div. Is one X to close the windows but show some html code like form.
See my jQuery code:
var myDivImg = $( "<div class="topImg"></div>" )
$(document).ready(function() {
$("#maisinfo").before(myDivImg, '<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$("#maisinfo").hide();
$("#show").bind("click",function(){
$("#maisinfo").slideToggle("slow");
return false;
});
});
I want to insert the html: <a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a> within .before() inside the div topImg in my HTML. I try create the div inside .before() but, jQuery create other same div.
Someone can help me please and make some explanation for I understand what I did wrong?
If you want to add something inside the DIV, you use .prepend() or .append(), depending on whether you want it at the beginning or end. .before() puts it outside the DIV, right before it.
$("#topDiv").prepend('<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$(document).ready(function() {
$(".topImg").append("<div id='maisinfo'></div>");
$("#maisinfo").before('<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>');
$("#maisinfo").hide();
$("#show").bind("click",function(){
$("#maisinfo").slideToggle("slow");
return false;
});
});
</script>
<div class="topImg">
<div class="topImgIcon">
<img src="img/bbbbb.png" class="topImgIcon"><span class="tittle">Chat Window</span>
</div>
</div>
You could insert the div with ".html('xxx')" or with .append/prepend('xxx').
$(document).ready(function() {
var myDivImg = $( "<div class="topImg"></div>" );
// or var myDivImg=$('.topImg'); // => if the element exists
var myInsertDiv='<a class="imgClose" href="javascript:window.close()"><img src="img/close.png"></a>';
// first method
myDivImg.html( myInsertDiv ); // replace all html in this div with the content from "myInsertDiv"
//second method
myDivImg.append( myInsertDiv );// add the html from "myInsertDiv" as last child in your "myDivImg"
//or
myDivImg.append( myInsertDiv );// add the html from "myInsertDiv" as first child in your "myDivImg"
});
EDIT:
to close your div use something like this
$('body').on('click','.imgclose',function(){
$('.topImg').slideUp('slow');//close your parent-main div
return false;
});

How to get cursor placed element from onclick button using javascript

I have contenteditable div in HTML5. I have a ul li inside the DOM. When I click on that button I want that cursor placed inside the li using javascript. How can I do that?
<span class="mT2 mL10 bullotIcon fR vam" onclick="iconClick(this)">clickButton</span>
<div id="editableEvent" class="w100p ht70 f13 textField w250 boxSizeBB whiteBg selev grayBdr oA" contenteditable="true" style="height: 100px;">
<ul>
<li>dafdsasdsdfasdfd</li>
<li>dfsfsdfdsfsdfdfdsfsdfsdfdsf</li>
<li>sdfsdfsdfsdfsdfdfsdffdf</li>
</ul>
</div>
function iconClick(obj){
if ($('#editableEvent').getSelection) {
console.log($('#editableEvent').getSelection().anchorNode.parentNode);
}
}
Normally my cursor was inside the content editable div. on click button i want the cursor placed element like 'li' Thanks in advance
Add code below after you click button.
document.getElementById("editableEvent ul li").style.cursor = "default";
To remove an LI that was clicked on, you can use an event's target property to work out what you clicked on then remove it.
Plain JS:
document.getElementById('editableEvent').onclick = function(e){
if(e.target instanceof HTMLLIElement){
e.target.remove();
}
}
jQuery:
$('#editableEvent').click(function(e){
$target = $(e.target);
if($target.is('li')){
$target.remove();
}
});
I am just providing links that may help you
https://stackoverflow.com/a/3976125/3979414 - to find the current position in contentEditable text.
https://stackoverflow.com/a/1211981/3979414 - to find the cursor mentioned tag
https://stackoverflow.com/a/4232971/3979414 - to remove the corresponding tag
you can also try:
$('li').on('click',function(){
$(this).remove();
});
On click li, I was add one class on it after button clicked i remove that class element
"Li clicked":
callLiFunction: function (obj){
$('#editableEvent').find('.liCreated').removeClass('liCreated');
$(obj).addClass('liCreated');
}
"button clicked":
funcCallDel : function() {
$('#editableEvent').find('.liCreated').remove();
}
Thanks for get some idea from you people.

Dynamically adding event handler to select box

I'm trying to dynamically add an event listener to a select box.
With this code I just don't get any response, so no alert box:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
$("sel1").on('change', function() {
alert(this.val());
});
table.append(row);
$('#mydiv').append(table);
Also, how can I add the select box between the td?
Currently, it's added between the tr, td simply isn't there.
Here is a fiddle
Updated Fiddle
You should use event delegation on() when you deal with fresh DOM added dynamically :
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
NOTES :
You should add id selector before sel1 it should be #sel1.
.val() is a jquery method you can't call it on javascript object like this.val() it should be $(this).val().
The current code will not add select inside td it will add it directely inside tr tag so you could replace :
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option>
<option>test2</option></select>');
By :
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>
test2</option></select></td>');
Hope this helps.
Working Snippet
var table = $('<table></table>');
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
$("#mydiv").on('change', '#sel1', function() {
alert($(this).val());
});
table.append(row);
$('#mydiv').append(table);
td{
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
Couple of points to note in your code
1) Wrong Selector $("sel1")
The problem in your code is $("sel1") you need to select by id using # so it should be $("#sel1"). So your code would be like
$("#sel1").on('change', function() {
alert(this.val());
});
2) Bind event after appending the HTML to DOM or Use Event Delegation
Your code should be places in this order Working Fiddle
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);// now the element is added to DOM so bind event
$("#sel1").on('change', function() {
alert($(this).val()); // note here I changes this.val() to $(this).val()
});
Or another option is using event delegation Working Fiddle
To add event's to dynamic elements use the event delegation
$('body').on('change',"#sel1", function() {
alert($(this).val());
});
3) To place the select tag inside td use the below syntax
var row = $('<tr></tr>').html('<td><select id="sel1"><option>test</option><option>test2</option></select></td>');
Wrap the td along with the select tag and not inside the tr Working Fiddle
You need to bind the change event after appending to the page:
var table = $('<table></table>');
var row = $('<tr><td></td></tr>').html('<select id="sel1"><option>test</option><option>test2</option></select>');
table.append(row);
$('#mydiv').append(table);
$("#sel1").on('change', function() {
alert(this.val());
});
And also you have forgotten the # id selector for "sel1"
There are three major issues in your code
1.The id selector must start with #
$("#sel1").on('change', function() {
2.You should bind the change listener only after you appended the element, because it just doesn't exist in the DOM before
3.With
$('<tr><td></td></tr>')
you'll get a jquery reference to the row (the <tr> element). Then with .html() you are replacing the content of the row (including the <td> of course)

Add new parent div and next a div inside this parent div

I want to do a simple manipulation but i don't understand why it's don't work i have a div :
<input type='button' value='validate' class='popupjq'>
And i want to add a parent div to this input and also a 'brother' div for have this result :
<div id = 'id_parent'>
<input type='button' value='validate' class='popupjq'>
<div id = 'id_brother'></div>
</div>
So i use this javascript :
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'>");
var divCache = $("<div id='toto'>");
$(this).wrap(divParent);
$(divParent).append(divCache);
});//bracket missing
My problem is that the parent div is create but not the brother div.
You can use insertAfter() to put the second element where you require:
$(".popupjq").each(function() {
$(this).wrap('<div id="id_parent" style="display: inline-block; position: relative;"></div>');
$('<div id="toto"></div>').insertAfter(this);
});
Example fiddle
You haven't closed your each-loop properly (check brackets).
You should specify the DIVs' HTML as strings.
Using "each" implies you're
planning to apply this method on several elements. In this case you
should work with classes instead of IDs in your DIVs' HTML, since IDs
are meant to exist exactly one time in the DOM.
You haven't addressed your parent DIV properly (see my approach).
http://jsfiddle.net/1yn8qgg3 (CSS with background colors to visually mark the DIVs)
$(".popupjq").each(function() {
var divParent = "<div class='class_parent'></div>";
var divCache = "<div class='class_toto'></div>";
$(this).wrap(divParent);
$(this).parent().append(divCache);
});
Hope this helps.
Do the following, to get the result
$(function(){
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'> </div>");
var divCache = $("<div id='toto'> </div>");
$(this).wrap(divParent);
$(this).append(divCache);
});
});
Fiddle

add and remove elements from form, 1st click works, subsequent clicks dont

I am trying to add/remove an element to a form based on a checkbox in a previous part of the form. My problem is, the first time a user clicks on anything in checkContact, the form is appended correctly. If the user unchecks the box, it is removed correctly. When the user re-clicks the checkbox, the element is not added..
$('.checkContact').click(function(){
var addInfo = "<div class='middleRow'><input type='text' id='"+val+"_name[]' name='"+val+"'_name[]'></div>";
if($(this).is(':checked'))
{
alert(addInfo);
$('#'+divId).append(addInfo);
}
else
{
$('#'+divId).detach();
// i have also tried .remove();
}
fiddle:
Fiddle
In the else part, you are removing the element $('#' + divId) from the dom tree instead of removing its content. You have to only empty the container element because in the if block you are adding the target markup to the container element.
$('.checkContact').click(function () {
var val = $(this).val();
var divId = val + '_div';
var addInfo = "<div class='middleRow'><input type='text' id='" + val + "_name[]' name='" + val + "'_name[]'></div>";
if (this.checked) {
//alert(addInfo);
$('#' + divId).html(addInfo);
} else {
//you are removing the container instead of removing its content
$('#' + divId).empty();
}
});
Demo: Fiddle
When you uncheck the box, you remove name_div from the DOM with .detach. So when you click the box again, the selector doesn't find anything, so there's nothing to append to.
Change .detach() to .empty()
DEMO
But perhaps a better method would be to hide and show the DIV, rather than add and remove the content.
In your code you have used detach() or empty(), it would remove the element from the DOM and after that you will not be able to insert html by using .html() method. Instead of using detach() or remove() you have to use .empty() or .html(''), this will keep the element in DOM, so you can again and again append the element.
$('.checkContact').click(function(){
var addInfo = "<div class='middleRow'><input type='text' id='"+val+"_name[]' name='"+val+"'_name[]'></div>";
if($(this).is(':checked'))
{
alert(addInfo);
$('#'+divId).append(addInfo);
}
else
{
$('#'+divId).html('');
//or $('#'+divId).empty();
}
});
see here:
http://jsfiddle.net/WYmVU/

Categories