Jquery add data to html before adding to DOM - javascript

I am building html on the fly need to add data before I add it to DOM. Since I am looping thru' lot of information, I would like to add the relevant data info along with the dom I am building instead of adding the html and then looping thru again to add the data.
result.forEach(function(record) {
html += '<div id ="' record.ID + '">test content </div> ';
//add data to above
});
I can do another loop here after adding it to DOM
$(body).append(html);
testresult.forEach(function(record) {
$("#" +record.ID).data(record);
});

Instead of concatenating strings to piece together your HTML, you may way to try something like this:
result.forEach(function(record) {
$('.selector').append(function () {
var $div = $('<div></div>');
$div.attr('id', record.testID).text('some text');
return $div;
});
});
This creates a new div jquery object for each item in result. You can use the record object to add attributes, data, text, etc to you object. It will be added the DOM when the callback passed into .append returns your new jquery DOM object.

Start trying to use jQuery to create your html elements so you can take fully advantage of jQuery and its plugins.
Ex:
var div = $("<div></div>") // create the element
.text("test content") // change the inner text
.attr("id", record.testID); // set the element id
div.appendTo("body");
You can check out [http://www.w3schools.com/jquery/] as a great source for learning jQuery.

You have quotes problem in the following line :
html += '<div id =record.testID' + '>test content </div> ';
________^______________________^___^_____________________^
You should fix that using double quotes because as it's now the string will be considered as '<div id =record.testID'.
html += '<div id="'+record.testID+'">test content </div>';
Or you could use separated definition :
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
$('body').append(div);
})
Hope this helps.
var result = [{testID: 1,testDATA: 'data 1'},{testID: 2,testDATA: 'data 2'},{testID: 3,testDATA: 'data 3'}]
var html='';
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
console.log(div.data('test'));
$('body').append(div);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to take an image from html table row

I face a problem, I can take the values from HTML table row and I can easily set them to another text box, but how we can take an image from HTML table row and how to set that into a div,
Summarize: I want to take an image from HTML Table row and set that to a div.
// For View data
$(document).ready(function() {
$("#dtBasicExample tbody").on('click', 'tr', function() {
$("#txtSelect").text("1 row selected");
var rowData = $(this).children("td").map(function() {
return $(this).text();
}).get();
$("#txtSId").val(rowData[0]);
$("#txtSName").val(rowData[1]);
$("#txtSPosition").val(rowData[2]);
$("#imgS").html(`<img src="images/'.rowData[3].'">`);
$("#txtSFacebook").val(rowData[4]);
$("#txtSTwitter").val(rowData[5]);
$("#txtSGoogleplus").val(rowData[6]);
});
});
You should rather be doing :
$("#imgS").html('<img src="images/'+rowData[3]+'">');
To concatenate in JS you need to use + and not .
You also need to use the character ' at the start and end of your string rather than using `

How to modify HTML attributes inside a variable that contains HTML?

I have a variable that contains some HTML elements & content:
var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';
What I'd like to do is modify the data-id within the #div-element.
What I've tried so far:
console.log($(data).find('#div-element').attr('data-id'));
This returns undefinied.
data = $.parseHTML(data);
console.log($(data).find('#div-element').attr('data-id'));
Tried to parse the HTML also, but it returns undefinied as well.
What am I missing here?
I'm using jQuery but a Javascript solution is just as good.
The issue is because you're using find() yet there is no root element in the HTML string you're specifying; all the elements are siblings. In this case you can use filter():
var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';
var id = $(data).filter('#div-element').data('id');
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Also note the use of data('id') over attr('data-id').
Create a dummy element div and set data as its innerHTML
var html = `<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>`;
var div = document.createElement( "div" );
div.innerHTML = html; //set the html string
//change the attribute of the id-Element
div.querySelector( "[id='div-element']" ).setAttribute( "data-id", "2" );
console.log( div.innerHTML );
In this case following will work.
$("<div>" + data + "</div>").find('#div-element').attr('data-id')

Inserting elements to appended elements using JavaScript or jQuery

I am fairly new to JS, and have created a little piece of script and it does exactly what I want which is find some elements then adds elements with data populated from via ajax....
So I go from this...
<select><select/>
to this...
<select>
<option value="{ajax value data}"> {ajax text data} <option/>
...
<select/>
using this piece of script...
filteredSelectIds.forEach(function (item) {
let itemId = '#' + item;
let itemData = item.split('-')[0] + 's';
$.each(data[itemData], function (i, color) {
$(itemId).append($('<option/>', {
value: color.optionValue,
text : color.optionText
}));
});
});
Now, what I am trying to do is at the same time add a Font Awesome icon to each element so I need to end up with something like this,,,,
<select>
<option value="{ajax value data}"><i class="fa fa-icon"> {ajax text data} <i/><option/>
...
<select/>
How would I do that??
I'm also new at JS, try this.
element = '<i class="fa fa-icon"> {0} <i/>'.format("{ajax text data}")
$('<option/>').append( element );
So #brk gave me this solution which worked, and would work for putting an Element inside another
"Create the option tag & i tag & first append itag to option tag and then append option tag to item"
filteredSelectIds.forEach(function (item) {
let itemId = '#' + item;
let itemData = item.split('-')[0] + 's';
$.each(data[itemData], function (i, color) {
var selOption = $('<option value="' + color.optionValue + '"></option>');
selOption.append('<i class="fa fa-icon">'+color.optionText+'<i/>');
$(itemId).append(selOption); }); });
However, although this placed the element inside the element as I wanted, and this could principle could probably be used to place any element within another, Tibrogargan correctly pointed to a question that makes the point that elements cannot be place within elements (Not really the Point of my question, but helpful). My solution was simply using the unicode for the Font Awesome icon and escaping it with \u then used \xa0 for additional spaces as follows:-
filteredSelectIds.forEach(function (item) {
let itemId = '#' + item;
let itemData = item.split('-')[0] + 's';
$.each(data[itemData], function (i, color) {
$(itemId).append($('<option/>', {
value: color.optionValue,
text : '\ue905 \xa0\xa0\xa0' +color.optionText
}));
});
});
Thanks!

Accessing dynamically appended div elements in jQuery

I need a suggestion on below scenario.
I have an object of items and dynamically building a html object as follows:
$.each(item,function(k, iteminner) {
html += '<td><div id="outerdiv">' + iteminner.Name + '</div>';
html += '<div id="clickme"></div></td>';
});
A table is built in this format, where each box will contain a name and button in each td. When a user clicks on a button of a cell I want to show the name respectively.What is it that I am missing here?
$('#clickme").click() {
alert($("#outerdiv").iteminner.name);
}
Assuming that id is unique for both the divs, like id="outerdiv" + k , how do I access element present in second cell, when second div id="clickme" + 2 is clicked?
ID's they have to UNIQUE
// Use class instead
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div>';
html += '<div class="clickme"></div></td>';
});
// You need to have event delegation here as a direct onclick wont be binded for the dynamically created .clickme
$(document).on("click", ".clickme", function(){
// You need to fetch the html of .outerdiv, so traverse to it first.
var _html = $(this).closest("td").find(".outerdiv").html();
alert(_html);
});
Firstly you are appending multiple elements with the same id to the DOM, which is invalid. You should change your HTML to use classes, like this:
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div><div class="clickme"></div></td>';
});
From there you need to use a delegated event handler on the .clickme elements (as they are dynamically created after the DOM has loaded) to traverse the DOM and find their sibling .outerdiv. Try this:
$(document).on('click', '.clickme', function() {
var name = $(this).siblings('.outerdiv').text();
// do something with name here...
});
Note that I used document as the primary selector above. Ideally you should use the nearest static parent element - I would suggest you use the same selector you use to append the html variable to.

jquery, add div with class definition

So I see here how to add a div and here how to add a class but I'm having trouble combining the two. I want to generate a whole bunch of div's with a specific class and id within the div sparkLineContainer.
I have the containing div
<div id="#sparkLineContainer"></div>
and I want to add a bunch of the following to it
<div id="#sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
// and so on
</div>
snippet - I didn't make it very far, I'm stumped
$('#sparkContainer').add("div"); \\ How do I add the id and class to this div?
\\ And as a repeat the function will it overwrite this?
The function I'm trying to do this with.
function renderSparklines (array1, sparkLineName, id) {
// array1 is the data for the spark line
// sparkLineName is the name of the data.
// Turn all array values into integers
arrayStringToInt(array1);
// Create new div of class sparkLines
$('#sparkContainer').add("div")
// Render new spark line to
$('.sparkLines').sparkline(array1, {width:'90px'});
var htmlString = ""; // Content to be added to new div
// GENERATE LITTLE SPARK BOX
htmlString +=
'<font class = "blueDescriptor">' + sparkLineName + '</font>'+
'<br>'+
'<font class = "greyDescriptorSmall">Ship to Shore</font>'+
'<br>'+
'<font class = "blackDescriptorSparkLine">' + array1[array1.length-1] + '</font>'+
'<font class = "greenDescriptorSparkline">(' + (array1[array1.length-1] - array1[array1.length-2]) + ')</font>' +
'<br>';
$('.sparkLines').prepend(htmlString);
}
add does not do what you think it does. You are looking for append or something similar.
You can create the div first and define its attributes and contents, then append it:
var $newDiv = $("<div/>") // creates a div element
.attr("id", "someID") // adds the id
.addClass("someClass") // add a class
.html("<div>stuff here</div>");
$("#somecontainer").append($newDiv);
You need .append or .prepend to add a div to the container. See my version below,
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer")
.append('<div id="id' +
($sparkLines.length + 1) +
'" class="sparkLines">Some Stuff Here</div>')
Also I noticed that you have id of the div as #sparkLineContainer. You should change it as below,
<div id="sparkLineContainer">
...
DEMO
You can add a div or any other tag along with class like:
$('<div/>',{ class : 'example'}).appendTo("p");
Probably the easiest way is to just modify the innerHTML:
$("#sparkLineContainer").append('<div class="sparkLine" id="id1"></div>');
There's other ways as well, but this is the method I generally use.

Categories