Creating and Adding content dynamically - javascript

I'm creating some ul and span tags dynamically. Now, I'm trying to add content dynamically as well through a click function. The tags gets created inside a ul but the content doesn't get inserted. Here is the code for it:
<div class="main"></div>
<div class="content-list"><ul class="information"> </ul></div>
Here's the Javascript with the function and the listener:
var $contentHandler = $(".content-list");
var $mainHandler = $(".main");
var $infoHandler = $(".information");
var circleCounter = 1;
$mainHandler.click(function() {
var htmlString = "<li class='" + circleCounter + "'> <span class='circle-color'> var color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </span> <br> <span class='circle-radius'> This is supposed to change </span> <br> <span class='circle'> This is supposed to change </span> </li>"
$infoHandler.append(htmlString);
updateList();
circleCounter++;
});
function updateList() {
var listItems = $('.information').find('li#' + circleCounter);
var len = circleCounter;
for (var i = 0; i < len; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + circleCounter + ";";
var updateStringCircle = "circle (" + circleCounter + " ," + circleCounter + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
radiusItem.text(updateStringRadius);
circleItem.text(updateStringCircle);
// divItem.text(updateString);
var $circleRadiusHandler = $(".circle-radius");
}
}
Any suggestions in how to make it work. Here's a JSFiddle for that:
http://jsfiddle.net/mauricioSanchez/wL6Np/1/
Thank you kindly,

You just need to change:
var listItems = $('.information').find('li#' + circleCounter);//this searches by id
//To:
var listItems = $('.information').find('li.' + circleCounter);//this searches by class`
//And remove:
var currentItem = circles[i];

Why are you trying to edit your HTML after you've defined it? Why not use a template like this:
var listItemClass = 'someclass',
typeOfColor = 'somecolor',
radiusOne = 'someradius',
radiusTwo = 'anotherradius';
var listItem = "<li class='{0}'> \
<span class='circle-color'> var color = \
<div class='circle-color-input' contentEditable autocorrect='off'> {1}</div> ; \
</span> \
<br> \
<span class='circle-radius'>{2}</span> \
<br> \
<span class='circle'>{3}</span> \
</li>";
listItem.format(listItemClass, typeOfColor, radiusOne, radiusTwo);
With the following format definition:
String.prototype.format = String.prototype.f = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
This way, you don't have to worry about finding certain elements within your predefined structure after the fact. You're just replacing certain parts with whatever you specify.

Related

Dynamically assign ID and attach data in JavaScript & jQuery using two nested for loops

I am having some trouble to get through this below jsfiddle task.
jsfiddle link
I want to do the same function using dynamic id.
I tried so many methods, but nothing works.
Please don't recommend to change the infrastructure. The page has been already designed the same kind of structure.
I need to achieve this same kind of function using two nested for loops with dynamic id.
HTML:
<div class="col-md-4" id="beforeDiv0">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId0" value="1000" />
</div>
</div>
<br/><br/>
<div class="col-md-4" id="beforeDiv1">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId1" value="1000" />
</div>
</div>
Javascript & jQuery:
$(document).ready(function(){
var newAmount = parseFloat(1000) + parseFloat(5);
for(var id=0; id<3; id++){
for (var i = 1; i < 3; i++) {
var html = '<tr style="height:50px;">';
html = html + '<td class="td-Amount" style="text-align: right; font-size: 15px; font-weight: bold;">';
html = html + 'Original: '+ '<span id="OrginalAmount' + i + '">' + 1000 + '</span><br/>' + 'New: <span id="Output' + id + "" + i + '">' + newAmount + '</span></td>';
html = html + '</tr>';
$(html).insertAfter("#beforeDiv" + id);
//var abc = id + "" + i;
//var xyz = '#textboxId' + id;
//var zyx = "Output"+id+""+i;
}
}
var myArr = new Array();
var myArr2 = new Array();
for(var id=0; id<3; id++){
var xyz = '#textboxId' + id;
myArr[id] = id;
for (var i = 1; i < 3; i++) {
myArr2[i] = i;
var calc = myArr[id] + "" + myArr2[i];
var zyx = "Output" + calc;
//below line is for dynamic id retrieval
/*
$(xyz).on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById(zyx).innerHTML = AmtChange;
});
*/
$("#textboxId0").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output01").innerHTML = AmtChange;
document.getElementById("Output02").innerHTML = AmtChange;
});
$("#textboxId1").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output11").innerHTML = AmtChange;
document.getElementById("Output12").innerHTML = AmtChange;
});
}
}
});
I looked at your code, and considered your comments, and if I understand you correctly, then something like this is what you are after:
$('input[id^=textboxId]').on("click change paste keyup", function() {
var id = $(this).attr('id');
id = id.replace(/\D/g,'');
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
/**
* The following could not really be simplified, because
* there are no defining data- attributes, or anything
* to identify the table rows as belonging to the textbox.
* When I tried to simplify the selection of "output" spans,
* a span with id Output111 would have been matched by Output11
* and Output1.
*/
$('#beforeDiv' + id).nextUntil('br').each(function(i,el){
$('span[id^=Output]', this).text(AmtChange);
});
});
I tested this on Codepen: https://codepen.io/skunkbad/pen/ayeVLp

Split large block of text into individual spans with individual ids

PLEASE DO NOT MARK THIS AS DUPLICATE! THIS IS THE ONLY PURE JAVASCRIPT APPROACH WITH INDIVIDUAL ID'S
How do I split a large block of text into individual spans with id's that go like this:
<span class="word" id="word0">Breaking </span>
<span class="word" id="word1">News. </span>
<span class="word" id="word2">Spring </span>
<span class="word" id="word3">is </span>
<span class="word" id="word4">here </span>
<span class="word" id="word5">to </span>
<span class="word" id="word6">stay. </span>
If the input was "Breaking News. Spring is here to stay."
I want to get the input from a specific div and output it into the same div. Please do not use jquery for this.
EDIT: Thanks to Scott Marcus, he gave me this code:
/* hw3a.js */
// your solution here
var button = document.getElementById('divideTranscript');
button.onclick = spanify();
var s = document.getElementById('transcriptText').innerHTML;
function spanify() {
var arry = s.split(" ");
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i) {
output += "<span class='word' id='word" + i + "'>" + arry[i] + "</span>" ;
}
s.innerHTML = output;
}
But it does not work?
var s = "Breaking News. Spring is here to stay.";
var arry = s.split(" "); // This will split on all single whitespaces
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i){
output += "<span id='word" + i + "'>" + arry[i] + "</span>" ;
}
alert(output);
// Or, to be more core DOM compliant
var d = document.createElement("div");
for(var i = 0; i < len; ++i){
var sp = document.createElement("span");
sp.setAttribute("id", "word" + i);
sp.textContent = arry[i];
d.appendChild(sp);
}
alert(d.innerHTML);

Make a html unordered list from javascript array

I'm having a bit of a problem. I'm trying to create a unordered list from a javascript array, here is my code:
var names = [];
var nameList = "";
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
nameList += "<li>" + names + "</li>";
document.getElementById("name").innerHTML = nameList;
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="submit()">
<br>
<br>
<div id="name"></div>
For example, if I post 2 names, Name1 and Name2 my list looks like this:
•Name1
•Name1,Name2
I want it to look like this:
•Name1
•Name2
If you look at your code, you are only creating one li with all your names as the content. What you want to do is loop over your names and create a separate li for each, right?
Change:
nameList += "<li>" + names + "</li>";
to:
nameList = "";
for (var i = 0, name; name = names[i]; i++) {
nameList += "<li>" + name + "</li>";
}
If you are interested in some better practices, you can check out a rewrite of your logic here: http://jsfiddle.net/rgthree/ccyo77ep/
function submit()
{
var name = document.getElementById("enter");
var theName = name.value;
names.push(theName);
document.getElementById("name").innerHTML = "";
for (var I = 0; I < names.length; I++)
{
nameList = "<li>" + names[I] + "</li>";
document.getElementById("name").innerHTML += nameList;
}
}
You are using an array, when you print an array JavaScript will show all the entries of the array separated by commas. You need to iterate over the array to make it work. However you can optimize this:
var names = [];
function displayUserName()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<input id="enter" type="text">
<input type="button" value="Enter name" onclick="displayUserName()">
<br>
<br>
<div id="name"><ul></ul></div>
In this example the HTML is syntactically correct by using the UL (or unordered list) container to which the lis (list items) are added.
document.getElementById("name").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
This line selects the div with the name: name and its first child (the ul). It then appends the LI to the list.
As #FelixKling said: avoid using reserved or ambiguous names.
<div>
<label for="new-product">Add Product</label><br /><br /><input id="new-product" type="text"><br /><br /><button>Add</button>
</div>
<div>
<ul id="products">
</ul>
<p id="count"></p>
</div>
var products = [];
var productInput = document.getElementById("new-product");
var addButton = document.getElementsByTagName("button")[0];
var productListHtml = "";
var abc = 0;
addButton.addEventListener("click", addProduct);
function addProduct() {
products.push(productInput.value);
productList();
}
function productList() {
productListHtml += "<li>" + products[abc] + "</li>";
document.getElementById("products").innerHTML = productListHtml;
abc++;
}

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

How do I specify where a span will be placed in a extjs grid?

I'm trying to understand the code I edited.
So I created the following variable
var headerPlaceHolderComponent = '()';
and placed it in the function below
formatTitle: function (containerWidth, containerNameTitle, aggregationTitle) {
// one character approximates to 6 pixels. So, dividing by 5.5
var maxCharacters = Math.ceil(containerWidth / 5.5);
var combinedTitle = containerNameTitle + aggregationTitle;
if (combinedTitle.length > maxCharacters) {
var numberOfCharsToTruncate = maxCharacters - combinedTitle.length;
aggregationTitle = aggregationTitle.replace(aggregationTitle.slice(numberOfCharsToTruncate), '...');
}
var formattedContainerNameTitle = '<span class="conatiner-name-title">' + containerNameTitle + '</span>';
var formattedAggregationTitle = '(<span class="aggregation-title-style-in-grid">' + aggregationTitle + '</span>)';
var headerPlaceHolderComponent = '(<span class="header-placeholder"></span>)';
var formattedCombinedTitle = aggregationTitle.length > 0 ? formattedContainerNameTitle + ' ' + formattedAggregationTitle + headerPlaceHolderComponent
: formattedContainerNameTitle + headerPlaceHolderComponent ;
return formattedCombinedTitle;
},
Currently the Span that I created renders out in HTML within the following span.
<span class="x-panel-header-text x-panel-header-text-default-framed" id="ext-gen1419">
<span id="ext-gen1525" class="header-placeholder"></span> <!--My Span -->
</span>
I would like my span to render within this div instead:
So my final rendered coded will look like this:
<div class="x-component x-box-item x-component-default" id="component-1196" role="heading">
<span id="ext-gen1525" class="header-placeholder"></span> <!--My Span -->
</div>
How can I specify where in the HTML my span will render?

Categories

Resources