Appending a dynamic div in another previously dynamically created div - javascript

I'm attempting to add a div within another div, both of which are dynamically created. I'm honestly unsure why it's not adding it in within the newDiv
(function ($){
$.fn.dropdown = function(){
return this.each(function(){
//Gather information
var id = $(this).attr("id");
//Get the original selection and keep it as a reference
var original = $(this);
//Create a new div with a predefined class and taking the ID from the original HTML.
var newDiv = $("<div id='"+id+"' class='dropDownJs' />");
//Remove the id from the original HTML
original.removeAttr("id");
//Encapsulate the original dropdown with a new parent div
original.wrap(newDiv);
//Create children divs within the parent div for each option within the selection HTML.
original.children().each(function(){
//Grab crucial values from the original.
//The value of the option
var val = $(this).val();
//The text from the option (label)
var text = $(this).text();
//Child divs to create
var child = $("<div class='dropDownJsChild'></div>");
newDiv.append(child);
});
});
}
}(jQuery))
For all intensive purposes, this jQuery is manipulating this HTML snippet
<select id="test" class="dropdown">
<option value="something1">Something 1</option>
<option value="something2">Something 2</option>
<option value="something3">Something 3</option>
</select>
To clarify further:
<script>
$(document).ready(function(){
$(".dropdown").dropdown();
});
</script>
Unfortunately, the newDiv.add(child) isn't working, and I've also tried doing newDiv.append(child) which has also failed.

Edit: As it turns out, the OP is trying to create invalid HTML structures, wrapping option tags inside div tags or whatever, so lets close this
Dont create a div with the same id as an existing one and wrap them like here: original.wrap(newDiv); remove the id before this
Secondly, youre using the add function which is not what you are looking for, rather use append:
newDiv.append(child);
the add function extends the jquery object newDiv by the child. append moves elements into others within the DOM.

You need to use after method of original element:
var child = $("<div class='dropDownJsChild' />");
original.after(child);
And the reason why you can't use newDiv to append new elements is obvious from documentation for wrap:
A copy of this structure will be wrapped around each of the elements in the set of matched elements.
So wrapping element is not original element anymore, it's a copy of it and does not represend the original node.

Related

clone select element and wrap

I clone multiple select elements in the following manner. This work perfectly:
Demo: https://jsfiddle.net/DTcHh/36308/
// get all items of specific class
var $selectedClassDiv = $('.to-clone');
// find select eles and clone into div
$('#cloned-list').html($selectedClassDiv.find('select').clone());
// loop through cloned select eles to set the correct selected option
$selectedClassDiv.find("select").each(function(i) {
var select = this;
$('#cloned-list').find("select").eq(i).val($(select).val());
});
The problem I have is that I would like to wrap these select items in a div that has a custom class. I've tried multiple methods to no avail, my latest attempts below.
Has no effect
$('#cloned-list').html($selectedClassDiv.find('select').clone().wrap('<div class="customClass"></div>'));
Demo: https://jsfiddle.net/DTcHh/36309/
Causes error
$('#cloned-list').html($selectedClassDiv.find('select').clone().parent().wrap('<div class="customClass"></div>'));
Demo: https://jsfiddle.net/DTcHh/36310/
I am interested in a solution that wraps a div around the select items. Cloning the parent div and adding a class isn't an option.
You could add it within your current loop:
https://jsfiddle.net/DTcHh/36311/
$selectedClassDiv.find("select").each(function(i) {
var select = this;
$('#cloned-list').find("select").eq(i).val($(select).val()).wrap('<div class="customClass"></div>');
});

Assign java scripts to cloned HTML element

I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

Add class name for generated Html using jquery

Below is html part
<li class="main_menu catagory_li" id="cat4">
<p class="ahead"><span class="heading">Item 4</span>
<span class="fright remove">close</span></p>
</li>
when i click close i copy the LI using below code,
$('.remove').live('click',function(){
var closed_elem_id = $(this).parent().parent().attr('id');
s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('li#'+closed_elem_id).remove();
console.log(s);
});
This one removes the LI in particular place and get the copy and store it in variable s.
My requirement is to add class called no-display in cloned copy like <span class="fright remove no-display">close</span> . I tried this many ways but it fails.
Kindly advice on this
NOTE : updated my question
A little optimized: http://jsfiddle.net/hKUd6/
Something like this:
$('.remove').live('click',function(){
var pLi = $(this).closest('li');
s = $('<div>').append(pLi.clone().addClass('no-display')).html();
pLi.remove();
console.log(s);
});
This whole thing is very sloppy. You don't need to use as much code as you have to accomplish the simple task you're attempting.
Try something like this:
$("li").on("click", ".remove", function(){
var $this = $(this),
liCont = $this.closest("p"),
parentLi = $this.closest("li");
liCont
.clone()
.wrap(
$("<div>").addClass("no-display")
)
.appendTo("body");
parentLi.remove();
});
What we do here is capture the click event on any .remove elements. We select the parent p (which we later clone to wrap with a div) as well as the parent li. We clone the p element (including its contents), wrap it with a div element (which we create using DOM scripting and add the class), and append the finished product to the body (you can change that if needed). We then remove the original li.
Try with this code, it should work:
$('.remove').live('click',function(){
var closed_elem = $(this).closest("li"); //get the li to be closed/removed
var clonedElem = closed_elem.clone().find("span.remove").addClass("no-display"); //clone the original li and add the no-display class to the span having remove class
closed_elem.remove(); //remove the original li
console.log(clonedElem);
});
Please check below lines of code.
first of all you need to get current class name using jquery:
$('li #cat4').find('span').each(function(){
var classname = $(this).attr('class');
$(this).addClass(classname+' no-display');
});
This is not a complete code of your task, but its just a code by which you can get a current class and then add more required string to it and set new class.
Thanks.

jQuery - Find next select element

What I am trying to do is populate data in a select element. I'm using the following code, where a user selects a SubjectCategory from one drop down, which then should populate the next select element's html. The handler itself is working just fine, it returns the correct html I need to place inside the select element.
Also, keep in mind that I eventually clone both of these select elements and will need to populate them accordingly.
The problem is that $elem is always returning null.
I'm guessing that it's a problem with this line of code, however not quite sure (keeping in mind that I'm also cloning these two select elements):
var $elem = $this.closest('div').prev().find('select');
$(".SubjectCategory").live("click", function () {
var $this = $(this);
var $elem = $this.closest('div').next().find('select');
var a = $this.val();
$.get("/userControls/BookSubjectHandler.ashx?category=" + a, {}, function (data) {
$elem.html(data);
});
});
<div class="singleField subjectField">
<label id="Category" class="fieldSml">Subject Matter</label>
<div class="bookDetails ddl"><select id="ddlSubjectMatter" class="fieldSml SubjectCategory"></select></div>
<label id="Subjects" class="fieldSml">Category</label>
<div class="bookDetails ddl" id="subjectMatter"><select id="ddlSubjects" class="fieldSml Subjects"></select></div>
</div>
You're searching inside the <label>, not the next <div> as you want. next only gets one element after the current one.
Try this: It searches for the first div next to your parent element.
var $elem = $this.closest('div').nextAll('div').first().find('select');
Given that the source element has an id of ddlSubjectMatter and the target select element has an id of subjectMatter, it may be a lot simpler to capitalise the first letter of the second id (i.e. make SubjectMatter) then you get the second element by:
var elem = document.getElementById(this.id.replace(/^ddl/,''));
It makes the element relationship independent of the document layout.
Incidentally, it is invalid HTML to have select elements with no options, not that it is a big issue.
Why are you creating an extraneous $this variable? Unless you've omitted code that requires it for a different scope, just call $(this). That might be causing the problem, too.

Categories