jquery clone work the first time but not later - javascript

Add row will clone the div but when I continue to click it doesn't clone single element but multiples, what's the flaw of the logic here?
$('#addRow').click(function () {
$(this).siblings('.elem').clone().appendTo($(this).siblings('.elem'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elem">elem</div>
<a id="addRow">+</a>

You want to only select one element, and the siblings('.elem') call is selecting all of them (except the current), including the cloned ones.
You can call first() after you call siblings() to select only one.
You also probably want to append them to the parent, not the same collection of all siblings.
var $clone = $(this).siblings('.elem').first().clone();
$clone.appendTo($(this).parent());
Alternatively, you could insertAfter() the last element ($(this).siblings('.elem').last()).

You are having multiple cloning because each time the element is cloned a new element with class="elem" is generated and hence all the elements having class="elem" are cloned on each click.
To address this problem use first() which only selects the first element with class="elem" and thus only one element is cloned on each click.
Below is a simplified version of the code,
$("#addRow").click(function(){
$(".elem").first().clone().appendTo("body");
});
Here is the JSFiddle for this solution
Instead of appending it to "body" use the id of the element to which you want to append the cloned elements. Hope this helps.

The problem is that your .elem selector matches more and more elements each time you click the button.
A way to resolve this is to keep a reference to one element and use that to clone and then append; additionally, it makes sense to group those elements in another <div> for easier reference.
jQuery(function() {
var $elem = $('#rows .elem'); // keep as reference
$('#addRow').click(function () {
$('#rows').append($elem.clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rows">
<div class="elem">elem</div>
</div>
<a id="addRow">+</a>

Clone only the first element and insert it just once, after the last instance.
$('#addRow').click(function () {
$(this).siblings('.elem:first').clone().insertAfter($(this).siblings('.elem:last'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elem">elem</div>
<a id="addRow">+</a>

Related

Change element's ID multiple times

so what I'm triying to achieve is that I want one element to append some other elements to div and change its ID attribute (or something similar).
i have tried something like this
$('#add3').click(function(){
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
and also tried something like this:
$('#add').click(function(){
var vari = $("<div id='add2'>add another user</div>");
$('#add').remove();
$('.third_row1').append(vari);
$('.third_row1').append('something to append');
});
so clicking one button (like second example) has no effect on third, fourth ... n click
same thing with the second example
thanks in advance for help
UPD
ok, so here's how I generate selects which I want to append
<jsp:useBean id="obj1" class="com.Users" scope="page"/>
<div class="third_row1">
<select name="mySelect1" id="mySelect1">
<c:forEach var="item1" items="${obj1.items}">
<option>${item1}</option>
</c:forEach>
</select>
</div>
all I want to do is to add same select, but with different ids and names
Since elements IDs are changed dynamically, you should use delegated event handlers with .on().
For example:
$(document).on("click", "#add3", function() {
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
If all these elements (#add, #add3) are inside page static element, it will be better to use this element instead of document for perfomance:
$("static_element_selector").on("click", "#add3", function() {
And just to note: since this inside event handler points to clicked DOM element, you can use this.id = "add4" instead of $('#add3').attr("id", "add4");. It is shorter and works slightly faster.

jQuery and first element in the clicked element

i have 2 div elements, and if i click on the first div then should the other div which is inside of the clicked div displayed, but i can't understand who it works, my jquery code is so:
jQuery('.infobutton').click(function(){
var clickedID = jQuery(this).attr('id');
jQuery(clickedID).children('div').toggle();
});
<div class="infobutton" id="infobtn1">
<div class="content">some content</div>
</div>
I get everytime right id, i tried also with .first(), .parent(), .children('.content')
It's possible to do this with jQuery?
Let's presume you have HTML like this:
<div id="container" class="infobutton">
Some content
<div>Some other content</div>
</div>
Now let's walk through your Javascript:
jQuery('.infobutton').click(function(){
Find elements with the class infobutton and assign a click handler. This works fine.
var clickedID = jQuery(this).attr('id');
Put the id of that element in the variable clickedID. The value of clickedID is now container.
jQuery(clickedID).children('div').toggle();
Run the jQuery selector on clickedID. Here we have the problem. This can be boiled down to jQuery('container'). This looks for an element with the tag name container, not with the ID container.
In fact, the solution to all of this is not to use the ID at all. Instead, you can build the jQuery object with this, which is a reference to the clicked element:
jQuery('.infobutton').click(function(){
jQuery(this).children('div').toggle();
});
Inside the event handler this will refer the element to which the handler was attached to
jQuery('.infobutton').click(function(){
jQuery(this).children('.content').toggle();
});
Demo: Fiddle
Use this
jQuery('.infobutton').click(function(){
jQuery(this).children('.content').toggle();
});
this refers to the current element inside the event .
your code will work as
use jQuery('#'+clickedID) instead of jQuery(clickedID)

Find element above another using jQuery

I'm trying to find the element using jQuery from the following html.
<ul class="gdl-toggle-box">
<li class="">
<h2 class="toggle-box-title"><span class="toggle-box-icon"></span>Volunteer Form</h2>
<div class="toggle-box-content" style="">
</div>
</li>
</ul>
What I'm looking to do is when the h2 is clicked find the li above the h2 add a class active to it. Tried a few different calls but no luck.
EDIT
The biggest issue is that there are multiple toggle boxes on a page so something like this works on pages with a single toggle but pages with multiple the result is they all open together.
var gdl_toggle_box = jQuery('ul.gdl-toggle-box');
gdl_toggle_box.find('li').each(function(){
jQuery(this).addClass('item');
});
gdl_toggle_box.find('li').not('.active').each(function(){
jQuery(this).children('.toggle-box-content').css('display', 'none');
});
gdl_toggle_box.find('h2').click(function(){
if( jQuery('.item').hasClass('active') ){
jQuery('.item').removeClass('active').children('.toggle-box-content').slideUp();
}else{
jQuery('.item').addClass('active').children('.toggle-box-content').slideDown();
}
});
You can use closest.
closest will match the first parent element that matches the selector traversing up the DOM tree.
Demo
$('h2.toggle-box-title').click(function(){
$(this).closest('li').addClass('active');
});
Try this.
$('h2.toggle-box-title').click(function(){
$(this).parent().addClass('newclass');
});
try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
On you click in the button you can use the event:
$("something").parent().find("h2.myClass");
// And if you want you can add class after you find you object
http://api.jquery.com/find/
Selecting an element's parent
In order to select an element parent, you can use the parent() function.
Try this:
$('h2.toggle-box-title').click(function() {
$(this).parent('li').addClass('active');
});
*to be more specific, you target the parent you would like to choose by specifying its selector
Check the jQuery API Documentation here
parent() - Get the parent of each element in the current set of matched elements,
optionally filtered by a selector.

How to .append() an object

I'm making a simple game in javascript and I would like to .append() a box. To serve as a bullet. But I'm stuck. This is what I have
var existingdiv1 = document.getElementById('bullet');
and
$("#test").click(function() {
$("div").append([existingdiv1]);
});
It wont create additional "divs" when I press the button "#test".
You will have to select the existing div (I guess this is the bullet?). Then append it.
Here's and example:
Working Demo
Javascript:
$("#test").click(function(){
$("#appendToThis").append($('#bullet').html());
});
Html:
<input id="test" type="button" value="click" />
<div id="appendToThis"></div>
<div id="bullet"><div>BANG</div></div>
You will see the word "bang" be appended everytime you click. You can remove it by using the empty() method on the test div.
From the .append documentation:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
It seems like you want to clone [docs] the element first:
$("div").append($(existingdiv1).clone());
// or simpler
$("div").append($('#bullet').clone());
Note though that if you have multiple div elements on your page, $("div") will select all of them and the element you pass to .append will cloned automatically (as stated in the documentation).
You should append the element only to a single div.
I believe you wanted to add a new div to the existing div, so your code has been reversed the append order. and you need wrap the existing div by $('#bullet')
Try this
$('#bullet').append('<div></div>');
You can use .clone()
$("#test").click(function(){
$("#appendToThis").append($('#bullet').clone());
});

jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked)
At the moment my jQuery is as follows.
$('.qacollapsed').hide();
$('.qa').click(function () {
$('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A)
Is there a way for it to only drop down the one that is clicked?
the HTML
<div class="qa">
<h4 class="question"> </h4>
</div>
<div class="qacollapsed">
<p> </p>
</div>
It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now..
Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, e.g.:
$('.qa').click(function () {
$(this) // start with the clicked element
.find('.qacollapsed') // find child .qacollapsed elements only
.slideToggle();
$(this).toggleClass('active');
});
This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods.
Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object
$('.qa').click(function () {
$('.qacollapsed', this).slideToggle();
//You could do $(this).find('.qacollapsed').slideToggle();
$(this).toggleClass('active');
});
Check out the jQuery selectors and why not just use $(this)?
$('.qacollapsed').hide();
$('.qa').click(function () {
$(this).toggleClass('active').next().slideToggle();
});
Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie
Var showIt = $(this).attr('id') + '_answer'
$('.qacollapsed').not('#'+showIt).hide();
$('#'+showIt).slideToggle;
That will hide all the divs without that ID and show the required one.
Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too.

Categories

Resources