i want to clone a element and insert on another position in the DOM. (So actually i just want to 'move' it).
On document ready some events get binded in a Plugin (which i don't want to edit) to a child element of the element i want to clone.
When i clone the element like this:
$('.FSGD-logo-slider-element-info').each(function(){
$number = $(this).attr('data-trigger');
$element = $(this).clone(true, true);
$('.FSGD-logo-slider-element[data-index="'+$number+'"]').after($element);
$(this).remove();
});
The element is cloned, but they don't react on any Events.
When i do it like this (Have a look on the third line with the live-method):
$('.FSGD-logo-slider-element-info').each(function(){
$number = $(this).attr('data-trigger');
$element = $(this).live().clone(true, true);
$('.FSGD-logo-slider-element[data-index="'+$number+'"]').after($element);
$(this).remove();
});
It is working. But the live method is removed since jquery 1.9, because of that i also get an error output.
I can't explain why that code is working and i don't have any idea to get it working without the live method.
I hope someone is able to help. That would be awesome.
i want to clone a element and insert on another position in the DOM. (So actually i just want to 'move' it).
Then just move it:
$('.FSGD-logo-slider-element-info').each(function(){
var $number = $(this).attr('data-trigger');
$('.FSGD-logo-slider-element[data-index="'+$number+'"]').after(this);
});
Example:
// Hook an event on a child of the info elements
$(".FSGD-logo-slider-element-info input").on("click", function() {
alert($(this).parent().attr("data-trigger"));
});
// Move the elements
setTimeout(function() {
$('.FSGD-logo-slider-element-info').each(function(){
var $number = $(this).attr('data-trigger');
$('.FSGD-logo-slider-element[data-index="'+$number+'"]').after(this);
});
$("p").remove();
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="FSGD-logo-slider-element-info" data-trigger="1">
Info One <input type="button" value="Click me">
</div>
<div class="FSGD-logo-slider-element-info" data-trigger="2">
Info Two <input type="button" value="Click me">
</div>
<div class="FSGD-logo-slider-element-info" data-trigger="3">
Info Three <input type="button" value="Click me">
</div>
<div class="FSGD-logo-slider-element-info" data-trigger="4">
Info Four <input type="button" value="Click me">
</div>
<div class="FSGD-logo-slider-element" data-index="1">
Element One
</div>
<div class="FSGD-logo-slider-element" data-index="2">
Element Two
</div>
<div class="FSGD-logo-slider-element" data-index="3">
Element Three
</div>
<div class="FSGD-logo-slider-element" data-index="4">
Element Four
</div>
<p>Elements will move after a second</p>
Side note: I added var in front of $number = ... above. Without it, your code was falling prey to The Horror of Implicit Globals (unless of course it was declared in a parent scope, but this is clearly used as a local, so that wouldn't make much sense).
Related
I'm trying to delete dynamically created elements each with their own delete button. This is the element that gets added with every button click. When the delete button of an element gets clicked I want that specific element to be deleted.
I use the following code to append the element:
$("#addsitem").click(function () {
$("#holdsitems").append('myFunction');
});
This is how I try to remove it:
$("#item").on("click", "#deleteitem", function() {
$("#item").remove();
});
I can only delete the elements that haven't been added.
This is all the relevant HTML code (myFunction) of the element:
<div id="item" class="itemdiv">
<form>
<div>
<div id="deleteitem">
<input type="button" name="Delete Button" value="Delete">
</div>
</div>
</form>
</div>
I'm rather new to jQuery and this is giving me headaches. Would appreciate it lots if someone could help me out!
You can use classes and the command .closest("selector") where this moves up the DOM tree until it finds the first element that matches that selector, you can then remove this.
You shouldn't be adding an id dynamically, unless you are adding an indices so that they are unique.
Demo
// Add new item on click of add button
$("#addsItem").click(function(event) {
// Stop submission of form - this is not necessary if you take it out of the form
event.preventDefault();
// Append new form item
$("#holdsitems").append('<div class="item-wrapper"><button type="button" class="deleteItem" >Delete</button></div>');
});
// Add DYNAMIC click event to class .deleteItem
$(document).on("click", ".deleteItem", function() {
// Move up DOM tree until first incidence of .item-wrapper and remove
$(this).closest(".item-wrapper").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item" class="itemdiv">
<form>
<div id="holdsitems">
<button id="addsItem">Add Item</button>
<div class="item-wrapper">
<button type="button" class="deleteItem">Delete</button>
</div>
</div>
</form>
</div>
Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";
Problem:
I want (after clicking on a button - this part is OK) to select the closest element with a class .my-textarea, but the using of prev() is not always possible, because the code is dynamic. Could you help?
Details:
I have this HTML code:
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
And my JS code (in on button with class "my-submit" click event) is:
var text = $(this).closest('.my-textarea').val();
But it's not working. I am getting undefined.
If I tried:-
var text = $(this).prev().val();
I will get the text of the text-area, but as I've mentioned, my code is dynamic and the order and number of elements will change. So, prev() is out of option.
Any idea how to make closest() work?
I always select parent and than search for child with class. That way your element can be placed virtually anywhere in parent.
$(this).parent().find('.my-textarea').val();
Need to Use siblings() instead of closest():-
$('.my-submit').click(function(e){
e.preventDefault();
var text = $(this).siblings('textarea').val();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="label">Description:</div>
<textarea class="my-textarea" name="my-textarea" rows="8" cols="40"></textarea>
<button type="button" class="my-submit" name="my-submit">Save</button>
</div>
You need to refer it using class
closest will traverse up the DOM tree to look for the element, while in this case textarea is sibling of the button.
$('.my-submit').click(function(){
var text = $(this).siblings('.my-textarea').val();
alert(text)
})
DEMO
I've three divs. Each div must increment its counter val upon clicking them.
HTML:
<body>
<content>
<div id="box1" class="v1" onclick="counter('box1')";>A : <span class="num">0</span></div>
<div id="box2" class="v2" onclick="counter('box2')">B: <span class="num">0</span></div>
<div id="box3" class="v3" onclick="counter('box3')">C: <span class="num">0</span></div>
</content>
</body>
Javascript:
function counter(id){
var id = document.getElementById(id);
$('#id').click(function () {
update($("span"));
});
}
function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
Here is the code demo
You are doing a lot of work that jQuery would do for you. If you change your class to simply box and use the ID's to style your content, you can do the whole thing like this:
<body>
<content>
<div id="box1" class="box">A: <span class="num">0</span></div>
<div id="box2" class="box">B: <span class="num">0</span></div>
<div id="box3" class="box">C: <span class="num">0</span></div>
</content>
</body>
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) + 1 );
});
});
Example: http://jsfiddle.net/ddvQU/1/
Some thoughts:
If a style is unique to a single element (now and in the future), you should be using IDs. Styles that are (or will be) common to multiple elements should use classes.
Using inline javascript onclick='blah()' is more difficult to manage, as it is not as easy to debug, does not allow for code reuse, and forces you to make updates in lots of places when you change code. It also makes you do nasty things like escaping quotes.
var id = document.getElementById(id); <= The whole reason we have jQuery is so that we don't have to do this. Simply do $('#'+id). (ok, maybe not the whole reason, but one of them).
You don't need to do the above if you attach a jQuery handler to your class of elements (see the first bullet). The handler will already have a reference to the object, even if it doesn't even have an ID.
I would use .on() instead of .click(), but as you look to be new to jQuery, get this to work first, and then look into why on() is better, and how to do it.
Assign a click function to your div that does:
$('#div_id').html(parseInt($('#div_id').html())++)
or something along those lines.
http://jsfiddle.net/4eqve/32/
Use a closure to store a counter variable for each DIV.
Attach a click handler.
Change counter function to this:
function counter(id){
update( $('#'+id+">span") );
}
http://jsfiddle.net/4eqve/24/
demo stores each count in data. One big thing that would have helped you is apply a common class to the elements you want to bind handler too as you'll see in this demo with added class "box"
If you're using jQuery then you might as well use the click handler it provides. You were quite close with your implementation, but you need to make sure that you're referencing the correct elements. I changed it so that you are passing the box div to the update function, that then selects the correct span from inside that div element.
// jQuery onclick for the boxes
$('#box1, #box2, #box3').click(function() {
update(this);
});
function update(j) {
var span = $(j).children('span');
var n = parseInt(span.text())+1;
span.text(n);
}
Here's the jsFiddle: http://jsfiddle.net/4eqve/29/
Fixed that for you.
It is much cleaner when you have clean html, and seperate the javascript to do the work.
<body>
<content>
<div id="box1" class="count-div">A : <span class="num">0</span></div>
<div id="box2" class="count-div">B: <span class="num">0</span></div>
<div id="box3" class="count-div">C: <span class="num">0</span></div>
</content>
</body>
$(function(){
$(".count-div").click(function(){
amount = 1;
value = parseInt($(this).find("span").html());
$(this).find("span").html(value+amount);
});
});
You can even clean that up more so you have less code. If you have any question ask me
http://jsfiddle.net/4eqve/33/
There are many bugs in your script. Not to mentione, the markup selection is quite vague.
With a little update to some mark-ups, we can do this with a tiny snippet.
$(".clicable").click(function() {
$(this).children("span").html(parseInt($(this).children("span").html()) + 1);
});
Check the demo here
Given:
<div>
<div id="div1">
<input type="radio" .. />
</div>
<div id="div2">
</div>
<div id="div3">
<button type="button">a button</button>
</div>
</div>
So, I am currently in the context of the <input> via its click event. I need to traverse this (using parent / children somehow) to select the button in div3 (without using a class, id etc) and enable/disable it. Any ideas?
Without any information about the logical relation between the elements, I can only make assumptions.
If the structure will remain exactly the same, then:
$(this).parent().next().next().find('button').attr('disabled', true);
If the target div is always the last element in the container, then:
$(this).parent().siblings(':last').find('button').attr('disabled', true);
If there is only ever one <button> in the container, then:
$(this).parents().eq(1).find('button').attr('disabled', true);
$('input').click(function() {
$(this).parent().parent().find('button').attr('disabled', 'disabled');
});
Though I highly recommend using some sort of class/ID to help out because DOM traversal can be brittle.
you can try this :
$('#div1 > input').click(function(){
$('#div3 > button').attr('disabled','disabled')
})
If the Html hierarchy never changes, then this will work.
$().ready(function(){
$('input').click(function(){
var elm = $(this).parent().parent().find('div').eq(2).find('button');
});
});