I was having an issue earlier cloning some HTML within a page I have now resolved the issue using the following JS Fiddle Below:
HTML:
<div id='1'>
<div class="template"> <!-- mark a clone target -->
...
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
Demo: http://jsfiddle.net/VcBrz/
EDIT** the first issue I had with cloning and clearing textboxes has been resolved resolved.
If you refer to the JSFiddle above - a new row is added every time a button is clicked on a form.
I am hoping to add another button to achieve the exact opposite, so rows can be removed on button click, and was wondering whether anyone could suggest an answer?
Try the following
var $template = $('.template');
$('#add').click(function() { // where add is the id of add button
$template.clone().insertAfter($template).find("input:text").val("");
});
$('#remove').click(function() { // where remove is the id of remove button
if($('.template').length>1)
$('.template').last().remove();
});
check this JSFiddle
Check this fiddle
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
Reference : clear text field value in clone object
Updated Fiddle
var $template = $('.template');
$('input[name=addNewRow]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
$('input[name=removeRow]').click(function() {
$('.template').filter(":not(:first-child)").get(-1).outerHTML = "";
});
Related
I have this code,
HTML and php
<?php for($i = 1; $i <= 5; $i++) { ?>
<div class="file-add-row" style="display:none;">Some content</div>
<?php } ?>
<div id="add-file-plus">Add File</div>
and the JS is
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add-row:visible:last'));
}
});
Now, my problem is, when I click the add button for the first time, the first 'file-add-row' div is displayed. But when I click the add button the second time, nothing happens on the page. Instead, it just completely removes that div from the dom.
I am just a beginner in jquery, so there might be things I overlooked. Anyone got any idea about what's going on ?
When you do:
$('.file-add-row:visible:last')
Just after:
$('.file-add-row:hidden:first').removeAttr("style")
They both refer to the same object. And if you try to insert an object after itself, it will end up removing itself from the DOM.
Change the JS to:
$('#add-file-plus').live('click', function () {
if($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var last_visible = $('.file-add-row:visible:last')
$('.file-add-row:hidden:first').removeAttr("style").insertAfter(last_visible);
}
});
Demo (Click on 'Add File'):
https://jsfiddle.net/woxd2jbf/1/
Here's a version without jQuery just plain JavaScript, it will work with divs just as it does with button, ul, and li. The details are commented within the source.
Key Methods
cloneNode()
appendChild()
PLUNKER
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--This <li> is a template to clone-->
<li class="row" style='display:none'>Some content</li>
<!--This is the empty list to be populated with clones-->
<ul id='list'>
</ul>
<!--This button will have an eventListener
that will execute a function when it is clicked-->
<button id="add">Add File</button>
<script>
/* Reference each element involved in process */
// The button
var add = document.getElementById('add');
// The list
var list = document.getElementById('list');
// The first li
var row = document.querySelector('.row:first-of-type');
/*
1. Button will listen for a `click`
2. Create a clone of the first li
3. Add clone as the last child of list
4. Set clone's display property to block
so it's visible
*/
add.addEventListener('click', function(e) {
var clone = row.cloneNode(true);
list.appendChild(clone);
clone.style.display = 'block';
}, false);
</script>
</body>
</html>
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add- row:visible:last'));, due to this line the issue is happening. because it first removes the style attribute which makes it visible so $('.file-add- row:visible:last') is returning itself. refactor to store the visible el's reference like below:
$(function () {
$('#add-file-plus').live('click', function () {
if ($('div.file-add-row:visible').length == 0) {
$('div.file-add-row:hidden:first').show();
} else {
var $el = $('.file-add-row:visible:last');
$('.file-add-row:hidden:first').removeAttr("style").insertAfter($el);
}
});
})
jQuery:
$('.clickhere').click(function(e){
e.preventDefault();
$(this).closest('.row').children('.abc').hide(); // working
$(this).closest('.row').children('.abc').children('input').value = ''; // not working
$(this).closest('.bookingrow').children('.addressbox').children('input').value(''); // alternative - not working
});
html
<div class="row">
<div class='abc'>
<input type='text' class='unknown' />
</div>
<div class="clickhere">hide</div>
</div>
my target is if i click the "clickhere" class, content under "abc" class will hide and whatever content added by customer on those input box, they will be clear.
same html used multiple time on the same form. that's why using "$(this)".
any solution? what i am doing wrong?
Thanks in advance.
You need to use .val() to set the value, jQuery methods normally will return a jQuery object not a dom element reference so you would not have a properly called .value.
$(this).closest('.row').find('.abc input').val('');
So
$('.clickhere').click(function (e) {
e.preventDefault();
//cache the value of .row since it is used multiple times
var $row = $(this).closest('.row');
$row.children('.abc').hide(); // working
$row.find('.abc input').val('');
});
I found a lot of info about this, but I haven't foundanything that could help me yet.
My problem is that I have got a div with its id and it supposes to be a container (#cont_seguim).
I have a menu on the right side which contains circles (made by css and filled with text), like following:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
where b and n are the format for background and text.
When I click a circle, this one must be added to the container (notice that each circle has got its own text), but I can't get that.
I made and array and used alert() to test that click works, and it does, but append() doesn't even work to print text, and I don't know why.
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
Thank you for your responses!
Your code seems to work fine (if you fix the different class name used in html vs script circulo_menu vs circle_menu)
Demo at http://jsfiddle.net/7jbUj/
To add the whole circle append the whole element and not its text by using .append(this)
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
Demo at http://jsfiddle.net/7jbUj/1/
To add a copy of the circle, so you can add multiple of them use the .clone() first..
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
Demo at http://jsfiddle.net/7jbUj/3/
Inside the click handler, this refers to the clicked element. And since you bind the click handler on the circle_menu element, this refers to that. You can use it directly for the appending or clone it to make a copy first..
unable to understand properly, hope below one can help you.
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
make sure classname and id name will remain same as html
Try using html() instead of text().
Try this: Demo
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
Try this:
$( ".container" ).append( $( "<div>" ) );
source
use
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
You could try
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
By this way the clicked circle element get added to div
I append the following content using jQuery to create a lightbox style popup that loads loads content using AJAX:
<div id="framebox-overlay">
<div id="framebox-wrapper">
<div id="framebox-nav-wrapper">
Previous
Next
</div>
<section id="framebox-content">
<!--AJAX to insert #single-project-wrapper content here-->
</section>
<div id="framebox-close">
<p>Click to close</p>
</div>
</div>
</div>
I am trying to get the appended next/previous links to work (.framebox-next and .framebox-prev as shown above), however the links are not triggering properly:
jQuery(document).ready(function(){
$('.framebox-trigger').click(function(e){
// Code that appends lightbox HTML and loads initial AJAX content goes here
});
// Code that isn't working:
$('body').on('click', 'a .framebox-next', function(e) {
e.preventDefault();
//remove and add selected class
var next = $('#portfolio-wrapper li.current-link').next('li > a');
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(next).addClass('current-link');
//fade out and fade in
var nexthref = $('#portfolio-wrapper li.current-link a').attr('href');
$('#single-page-wrapper').fadeOut('slow', function(){
var current = $('#portfolio-wrapper li.current-link a');
$(this).load(nexthref + " #single-page-wrapper", function(){
$(this).fadeIn('fast');
});
});
return false;
});
});
This last bit of code is not doing anything to the appended link .framebox-next. I have looked for other answers, and it seems that the .on() method should be effecting appended content.
Any help or input would be great.
Your selector is wrong for .framebox-next. You have a space between a and .framebox-next which would mean .framebox-next needs to be a child of the a element.
Use this selector instead:
$('body').on('click', 'a.framebox-next', function(e) {
...
}
When I try to clone a textarea by using cloneNote(true), the cloned textarea is not editable. Does anyone know how to resolve the problem? The sample codes show as following:
<html>
<head>
<script type="text/javascript" src="/javascripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode : "textareas",
});
</script>
<script type="text/javascript">
testclonenode = {
addAbove : function (element) {
var rowEl = element.parentNode.parentNode.parentNode;
var rowElClone = rowEl.cloneNode(true);
rowEl.parentNode.insertBefore(rowElClone, rowEl);
return false;
}
};
</script>
</head>
<body>
<table>
<tr><td>
<textarea name="content" style="width:100%">this is a test </textarea>
<p> <button onclick='return testclonenode.addAbove.call(testclonenode, this);'> Add above </button>
</td></tr>
</table>
</body></html>
It does not work that way. Also, it is impossible to move a tinymce editor using dom manipulation.
The tinymce wiki states the following:
mceAddControl
Converts the specified textarea or div
into an editor instance having the
specified ID.
Example:
tinyMCE.execCommand('mceAddControl',false,'mydiv');
So when you clone a textarea there is another problem: You will have the same id twice which will result in errors accessing the right tinymce instance.
I got this to work by using an ID which is incremented each time my clone function is triggered, so
var insertslideID = 0;
function slideclone() {
$('<div class="slides"><textarea name="newslide['+insertslideID+'][slide_desc]" id="mydiv'+insertslideID+'"></textarea></div>').insertAfter('div.slides:last');
tinyMCE.execCommand('mceAddControl',false,'mydiv'+insertslideID);
insertslideID++;
}
$('input[name=addaslidebtn]').click(slideclone);
Seems to work.
A wee bit tidier, I just use a number for my id - copy1 is the name of my button - I add the new element to the end of my container.
var count = 0;
$("#copy1").click(function(){
var newId = count;
$( "#first" ).clone().appendTo( "#container" ).prop({ id: newId, });
tinyMCE.execCommand('mceAddControl',false,newId);
count++;
});
I ran into a similar problem, except my element IDs (not just textareas) could be anything, and the same ID was always appearing twice. What I did is supposed to be horribly inefficient but there was no noticeable performance loss with dozens of elements on the page.
Basically I removed the TinyMCE ID first (uses jQuery):
$(new_element).find('.mce-content-body').each(function () {
$(this).removeAttr('id');
});
Then I reinitialized TinyMCE for all relevant elements.