How to get jQuery elements after declairation - javascript

I have created Tr with jQuery as below
var elemTr = $("<tr>", {
});
var elemEmpName = $("<div>", { }).data('otherDtls', {
recordId: 10
});;
Then in elemTr appended elemEmpName
elemTr.append(jQuery("<td>", {}).append(elemEmpName));
There are n no of elemTr which will be displayed inside Table
Now if I have "elemTr" -- How should I get "elemEmpName" which is present inside it, So I can get 'otherDtls' associated with it.

elemTr.find('td div').data('otherDtls')

You can use initial reference to do that.
// wrap it in jQuery so it becomes a collection
var elemEmpName = $("<div>", { }).data('otherDtls', {
recordId: 10
});;
// append to the DOM
elemTr.append(jQuery("<td>", {}).append(elemEmpName));
// do stuff, using the initial reference
$(elemEmpName).find('otherDtls');//do something

Related

jQuery read data from event

Here I have a problem:
I created one div and passed some data into it:
var div = $("<div />");
$.data(div, "a", 1);
div.on("click", function(event) {
console.log($.data(event.target, "a")); // print undefined
});
It looks like I could not retrieve data bound with an UI element this way. I would like to know why and whether there is any alternative for this - get a piece of data associated with an UI element within an event.
Thanks!
Try this ;-)
var div = $("<div>clic</div>").appendTo('body');
div.data("a", 1);
div.on("click", function() {
console.log($(this).data("a"));
});
JsFiddle : http://jsfiddle.net/t3n8y2xz/

Create element inside of parent element in Dojo

I can create a div inside the body like so:
var n = dojo.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.body());
I would like to create a div inside of my parent element such as this:
<div id="parent"></div>
I have tried this but it doesn't seem to work:
var n = dojo.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.query('#parent'));
How can I create my div inside of my parent div which already exists in the DOM?
The solution you posted is entirely valid. A couple of alternatives:
No need to look up the dom node, you can pass in a String (the id of the node)
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML: "<p>helloWorld</p>" }, 'parent');
});
Or you could construct the node and place it later using domConstruct#place:
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML: "<p>helloWorld</p>" });
domConstruct.place(n, 'parent');
});
domConstruct#place can also take an optional position parameter. The API Docs have more information on it
Should you need to target a class instead of a element id, I found the following to be and effective and easy to maintain method:
require([
'dojo/query',
'dojo/dom-construct'
], function(
query,
domConstruct,
){
var parent = query('.someClass')[0];
var child = domConstruct.create('div', { innerHTML: '<p>helloWorld</p>'});
domConstruct.place(child, parent, 'position');
});
Given it is always better to target an id instead of a class, but in cases when you are relying on outside libraries that isn't always viable.
The way I did it was this (I am open to any other solutions):
// dojo 1.7+ (AMD)
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.byId('parent'));
});
// dojo < 1.7
var n = dojo.create("div", { innerHTML: "<p>helloWorld</p>" }, dojo.byId('parent'));

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().
I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.
Here's the entire code based around it.
var setColors = function(){
getColors = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
//console.log(colors);
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
addColors();
}
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
return getColors();
}
$(function(){
setColors();
});
addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?
You are missing parentheses on the children method:
var el = $('#picker').children();
Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
A few issues:
missing end semi-color
missing parentheses on .children()
children() returns a jQuery object, no need for $(el)
Updated:
window.addColors = function(){
var $el = $('#picker').children();
$el.each(function(){
// do stuff here, but could attach each() to above, after children()
});
};

Select2 Dynamic elements not reacting to event

I am using Select2 which works great. However I am using below code to create new dynamic select2 drop down but they do not react/open when clicking on them.
var relationshipcounter = 0;
$('#AddMoreRelationships').click(function () {
var $relationship = $('.relationship'); // div containing select2 dropdown
var $clone = $relationship.eq(0).clone();
$clone[0].id = 'id_' + ++relationshipcounter;
$relationship.eq(-1).after($clone);
$relationship.find('select').trigger('change'); // not working
});
Screenshot:
JSFIDDLE:
http://jsfiddle.net/pHSdP/133/
I had this exact problem and, of course, the first thing I tried was a deep copy with data:
el.clone(true,true);
Which did not work. Instead the best method I found was:
el=other_el.clone()_etc; // cloning the old row
el.find('.select2-container').remove();
el.find('select').select2({width: 268});
el in both of these snippets is the div row that contains the select and so the Select2 element.
Essentially what I do in the second snippet is remove the "old" select2 which will always have the class of .select2-container and then recreate it on all found select elements within my new row.
You need to call clone with the true argument to copy over events and data as well. Otherwise only the element gets cloned, not the events that are bound to it.
$relationship.eq(0).clone(true);
Docs:http://api.jquery.com/clone/
Ok so issue is resolved, fiddle:
http://jsfiddle.net/WrSxV/1/
// add another select2
var counter = 0;
$('#addmore').click(function(){
var $relationship = $('.relationship');
var $clone = $("#RelationshipType").clone();
$clone[0].id = 'id_' + ++counter;
$clone.show();
$relationship.eq(-1).after($clone);
$clone.select2({ "width" : "200px" });// convert normal select to select2
//$('body').select2().on('change', 'select', function(){
// alert(this.id);
//}).trigger('change');
return false;
});
After cloning your object you have to reassign event for em:
var $clone = $relationship.eq(0).clone();
$clone.on("click", function_name);
Use .on to bind dynamically inserted elements to events like
$('body').on('click','#AddMoreRelationships',function () {
});

Using jQuery to retrieve IDs of several DIVs and store in an array

I'm currently working on a "template" creation system with html, jQuery and PHP. So the interface is very basic, buttons that currently add divs, these divs are to have content such as buttons, textareas, checkboxes and such.
When I click a button, the div is added; now i also want to store this new div ID into an array with jQuery and at the same time output this array into a separate div with the ID of overview.
My current script looks like this:
function getSteps() {
$("#template").children().each(function(){
var kid = $(this);
//console.log(kid.attr('id'));
$('div.overview').append(kid.attr('id'))
});
}
$('button').on('click', function() {
var btnID = $(this).attr('id');
$('<div></div>', {
text: btnID,
id: btnID,
class: item,
}).appendTo('div.template');
});
$(document).ready(function() {
getSteps();
});
Now, the function getSteps is where I want to retrieve the ID's of all my divs and store them into an array. When I click one of my buttons, I want them to add a div with an ID into my #template div.
I get an error in my console in chrome:
Uncaught ReferenceError: item is not defined
(anonymous function)createtemplate.php:111
f.event.dispatchjquery.min.js:3
f.event.add.h.handle.i
I'm a bit lost and would love a push into the right direction. Thank you.
You could do (to retrieve the ID's of all the divs and store them into an array. )
function getSteps() {
var ids = [];
$("#template").children().each(function(){
ids.push(this.id);
});
return ids;
}
$(document).ready(function() {
var arrayOfIds = getSteps();
});
You get that error because you're trying to use a variable called item that doesn't exist. I guess you want to give a class called item, in which case you should write
class:"item",
Also, you're appending the new divs to a element with class "template", and your getSteps function is searching for an element with id "template".
Think that with your code, the getSteps function executes once, when the DOM is ready. If you want to refresh the list of id's every time you add a div, you should do it inside your code for click event:
function getSteps() {
$('div.overview').empty();
$(".template").children().each(function(){
var kid = $(this);
//console.log(kid.attr('id'));
$('div.overview').append(kid.attr('id'))
});
}
$(document).ready(function() {
$('button').on('click', function() {
var btnID = $(this).attr('id');
$('<div></div>', {
text: btnID,
id: btnID,
class: 'item',
}).appendTo('div.template');
getSteps();
});
});

Categories