how to add data dynamically in jQuery? [duplicate] - javascript

This question already has an answer here:
How to add data dynamically with jQuery?
(1 answer)
Closed 8 years ago.
Can you please tell me how to add data dynamically? I am not able to make same as static.
http://jsfiddle.net/eHded/1537/
Please check this fiddle and open panel it show menu as well as submenu options.
Now I need to make same on button click. I have add button. I want add menu option (which is submenu of Additem in panel) can we do this.
I get the button click event, but that is not working fine.
http://jsfiddle.net/eHded/1538/
$('#add').click(function(){
// alert('e')
$('#tree li').append('<ul><li> <span>jjjj</span><ul>')
var tree = $('#tree').goodtree({'setFocus': $('.focus')});
})

Try this instead:
$('#add').click(function(){
var data = $('#tree li').html();
$('#tree li').html(data+'<ul><li> <span>jjjj</span><ul>')
var tree = $('#tree').goodtree({'setFocus': $('.focus')});
});
JsFiddle

You did not close your <ul> and <li> tag.
Also, you probably don't want to add the new element to every <li> in the tree.
Try the following instead (http://jsfiddle.net/eHded/1541/):
$(function() {
var tree = $('#tree').goodtree({
'setFocus': $('.focus')
});
$('.slider-arrow').click(function() {
var anchor = this;
var removeClass = "show";
var addClass = "hide";
var diff = "+=300";
var arrows = "«";
if ($(anchor).hasClass("hide")) {
diff = "-=300";
removeClass = "hide";
addClass = "show";
arrows = "»";
}
$(".slider-arrow, .panel").animate({
left: diff
}, 700, function() {
// Animation complete.
$(anchor).html(arrows).removeClass(removeClass).addClass(addClass);
});
});
$('#add').click(function() {
$('#tree').children().last().append('<ul><li><span>jjjj</span></li></ul>');
$('.goodtree_toggle').off();
$('#tree').goodtree({
'setFocus': $('.focus')
});
})
});
There also seems to be a problem with the goodtree plugin you are using.
The items only expand every second time you click them.
Ideally the plugin would use event delegation to make sure that the expanding still works even if you change the tree, without having to re-initialize. Since you re-initialize the tree after every insertion, there are multiple event handlers attached to the nodes. So when you have an odd number of nodes inserted, it will toggle the element an even times (since you initialized it in the very beginning when it was empty), giving you no result.
You can fix it by removing all event handlers on the toggle before you re-initialize:
$('.goodtree_toggle').off();
I would really look for a better plugin instead.

Related

Why is my jQuery not allowing me to toggle classes?

I have a series of custom Chevron elements that I'm going to use as buttons on my site. I've managed to set up the jQuery so that the clicked chevron/button is given a class="selected" which I then use to add custom styles. If I click any other chevron then the selected class is removed from the first chevron and added to the last chevron that was clicked. All of this works fine. I have another link that can be clicked to remove the class from all of the chevrons. What I'm trying to do now is to enable the .toggle(Class) function on jQuery so that I can also remove the class="selected" by clicking the same element twice.
My jQuery code:
$(function () {
$('#chevrons > ul > li > a').click( function(){
$('#chevrons .selected').removeClass('selected');
$('#show-all').removeAttr("style");
$(this).toggleClass('selected');
});
});
$(function () {
$('#show-all').click( function(){
$('#chevrons .selected').removeClass('selected');
$(this).css('color', '#FECF2A');
});
});
I've tried the toggle without the rows:
$('#chevrons .selected').removeClass('selected');
$('#show-all').removeAttr("style");
And it works fine. I assumed (perhaps incorrectly) that the jQuery would execute line-by-line and therefore the last thing to execute. But perhaps the first line above is removing the "selected" attribute from all of the chevrons and then the last line will only ever add the class.
What am I doing wrong here?
JSFiddle: http://jsfiddle.net/oqs4nycj/1/
Just exclude the clicked item from the class removal using not():
$('#chevrons .selected').not(this).removeClass('selected');
Applying this fix to your own JSFiddle (looks very cool by the way) you get this:
http://jsfiddle.net/qsnkqhp8/1/
JSFiddle:
http://jsfiddle.net/gopj0hyj/
Edit. I did not read the question carefully enough. Sorry. I have edited the code to deselect by clicking twice.
jQuery(function ($) {
// Variables are your friends - the $ preface tells us its a jQuery object
var $chevrons = $("#chevrons");
var $buttons = $chevrons.find('a');
var $show_all = $('#show_all');
// We bind a handler to the parent $chevrons element
// this is good for performance
// It will also bind the handler to elements dynamically added with ajax.
$chevrons.on('click', 'a', function(e){
var $old_selection = $buttons.filter('.selected');
var $clicked = $(this);
// Ensure that no button is selected
$buttons.removeClass('selected');
// Checks if button already was selected.
if ($clicked.get(0) !== $old_selection.get(0)) {
// select the clicked button
$clicked.addClass('selected');
}
$show_all.removeClass('active');
// prevents the browser from scrolling to top.
e.preventDefault();
});
$show_all.on('click', function(){
$buttons.removeClass('selected');
$(this).addClass('active');
});
});

How to handle an indefinite number of events?

So say I have some code that creates an indefinite number of comments in a main section of the page, such as
function createcomments(comments) {
var main = document.getElementById("main");
for (var i = 0; i < comments.length; i++) {
var comment = document.createElement("quoteblock");
comment.innerHTML = comments[i];
main.appendChild(comment);
comment.classList.add("comment");
}
}
And every time a visitor to my page hovered over a comment the background would turn red or something:
window.onload = function() {
var comments = document.querySelectorAll(".comment");
// code for handling .onmouseover and .onmouseout
// for each element in the array
}
How would I do that? I think there is a way to do it with jQuery, but I was wondering if there's a way to do it with JavaScript.
In jQuery there are this two helper functions delegate() and live().
They work as nicely described in this blog post.
Actually you can attach an eventHandler to a parent element that is than listeing to all mouse events (and other events). Using delegation you then check on the parent elements eventHandler if the event is coming from a specific child.
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
here we add some simple html, but we dont attach to the span element for a click handler, but to the div. in the div eventHandler we then check, what target actually got clicked
var divs = document.querySelector("ul");
divs.addEventListener("click", function(ev) {
if (ev.target.tagName === "LI")
console.log("A list element (" + ev.target.innerText + ") was clicked");
});
The whole reason behind this delegation is performance. also, if you remove or add items dynamically, the event handling works as expected without any additional work.
If you dont want to use the whole jQuery for this simple step, I still suggest you use some framework, as it is always better to use community support than reinventing the wheel
try http://craig.is/riding/gators, looks nice :)

Adding New Div In Editable Mode

I have following JsFiddle for editing a Div, now I some how want too add a div which in edit mode by default.
When i click on Add New div,new div is added and then it can be edited by clicking Edit .
But i was wondering is there a way when i click on ADD New Div the div should be by default in Edit mode. Is there any way i can achieve it.
Following is Js Fiddle
Thanks For Help :)
Change your function as follows:
$("#add").click(function () {
$('#accordion').prepend($("#appendpanel").clone().removeAttr('id').find('.panel-title, .panel-collapse').attr('contenteditable',true).css('border','2px solid'));
});
check this JSFiddle
Updated Fiddle as per comments
Note:
There are other neat ways for doing what you want.
You can simply keep a hidden editable div, add its clone and make it visible..
Or create a function that dynamically adds the mark up you need..
Side notes: Please avoid using inline-css, here is why: Why Use CSS # MDN
for changing style attributes jQuery has a dedicatedcss() function
You don't need two $(document).ready() functions
Not a one-liner, but does the job ;)
$("#add").click(function () {
var clone = $("#appendpanel").clone().removeAttr('id');
$('#accordion').prepend(clone);
// trigger a click event on the button, which makes the required div's content-editable
clone.find("#edit1").trigger("click");
});
Updated fiddle
Updated:
Use this code in $('#accordion').on('click', '.delete-link', function () {
var children = $(".panel");
// get those not hidden
children = children.filter(
function(index){
return children.eq(index).css("display") !== "none";
}
).length;
if(children === 1){ // the only child left is "Add new div"
$("#message").show(500);
}
And this in $("#add").click(function () {
$("#message").hide(500);
Updated fiddle

How to append the div element in jquery if don't exist

I am adding the form my current list in a div box at the bottom of the table.
I am appending the div box when someone clicks on add button.
But when i click add button multiple times , then many div boxes are appended.
Is there any way that no matter how many times I click the button, only one instance gets append to div box.
This is my code
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);
attach your listener using .one().
$("button").one('click', function(){
// Your code
});
Read more: http://api.jquery.com/one
This is under the assumption that you're using jQuery 1.7+
One simple solution would be having a boolean flag that you can toggle once your button is clicked. Additionally, there is actually a jQuery function that provides this exact functionality.
It's called one() -
Attach a handler to an event for the elements. The handler is executed
at most once per element.
So your code would look something like this -
$("#someTrigger").one('click', function(){
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);
});
The boolean method is also very simple -
var wasClicked = false;
$("#someTrigger").on('click', function(){
if (wasClicked == false){
// append your form
wasClicked = true;
}
});
Reference -
one()

how to remove all ClientEvents from anchors in an HTML String with jQuery

I've been struggling with what seems to be a simple problem for a few hours now. I've written a REGEX expression that works however I was hoping for a more elegant approach for dealing with the HTML. The string would be passed in to the function, rather than dealing with the content directly in the page. After looking at many examples I feel like I must be doing something wrong. I'm attempting to take a string and clean it of client Events before saving it to our Database, I thought jQuery would be perfect for this.
I Want:
Some random text click here and a link with any event type
//to become:
Some random text click here and a link with any event type
Here's my code
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv).find('a').unbind();
return $(myDiv).html();
}
My results are, the onClick remains in the anchor tag.
Here's a pure Javascript solution that removes any attribute from any DOM element (and its children) that starts with "on":
function cleanHandlers(el) {
// only do DOM elements
if (!('tagName' in el)) return;
// attributes is a live node map, so don't increment
// the counter when removing the current node
var a = el.attributes;
for (var i = 0; i < a.length; ) {
if (a[i].name.match(/^on/i)) {
el.removeAttribute(a[i].name);
} else {
++i;
}
}
// recursively test the children
var child = el.firstChild;
while (child) {
cleanHandlers(child);
child = child.nextSibling;
}
}
cleanHandlers(document.body);​
working demo at http://jsfiddle.net/alnitak/dqV5k/
unbind() doesn't work because you are using inline onclick event handler. If you were binding your click event using jquery/javascript the you can unbind the event using unbind(). To remove any inline events you can just use removeAttr('onclick')
$('a').click(function(){ //<-- bound using script
alert('clicked');
$('a').unbind(); //<-- will unbind all events that aren't inline on all anchors once one link is clicked
});
http://jsfiddle.net/LZgjF/1/
I ended up with this solution, which removes all events on any item.
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv)
.find('*')
.removeAttr('onload')
.removeAttr('onunload')
.removeAttr('onblur')
.removeAttr('onchange')
.removeAttr('onfocus')
.removeAttr('onreset')
.removeAttr('onselect')
.removeAttr('onsubmit')
.removeAttr('onabort')
.removeAttr('onkeydown')
.removeAttr('onkeypress')
.removeAttr('onkeyup')
.removeAttr('onclick')
.removeAttr('ondblclick')
.removeAttr('onmousedown')
.removeAttr('onmousemove')
.removeAttr('onmouseout')
.removeAttr('onmouseover')
.removeAttr('onmouseup');
return $(myDiv).html();
}

Categories