how to apply style on dynamically generated element - javascript

function createList(arrunique, arrayout) {
for (i = 0; i < arrayout[0].length; i++) {
var divIdC = i;
var divIdT = i + 10;
$('#tb').append('<select name="combo" style="float:left; width:100px;" id="' + divIdC + '" onchange="getComboVal(this,' + divIdC + ')"></select>');
$('#tb').append('<input type="text" name = "textBox" style= "width:100px;" id="' + divIdT + '" onkeyup="validate(this,"' + divIdT + '") value="0">');
var select = document.getElementById(divIdC);
select.options[select.options.length] = new Option("Select " + arrunique[i][0]);
for (j = 1; j < arrunique[i].length; j++) {
select.options[select.options.length] = new Option(arrunique[i][j]);
};
};
}
In this code I want to generate a combo box and a textbox and I want to apply some style sheet attribute or any class. How can I do this. Its not working.

There are many, many ways of styling a javascript created element. Here are a few.
Click here for live demo.
var myElem = document.createElement('div');
myElem.style.color = '#FFF';
with jQuery:
var $myElem = $('<div></div>');
$myElem.css('color', '#FFF');
or jQuery css object syntax (for passing multiple styles)
$myElem.css({display: 'block', background: '#000'});
Rather than adding the style after creating the element, you may also consider just adding a class to the element after creating it and styling this class in your css file.
CSS file:
.myElem {
color: #FFF;
}
myElem.className = 'myElem';
or
$myElem.addClass('myElem');

$('#tb').append('<input type="text" class="YOURCLASS" name = "textBox" style= "width:100px;" id="'+divIdT+'" onkeyup="validate(this,"'+divIdT+'") value="0">');

See this simplified jsFiddle. Ensure that the console is not generating an errors, and that you're calling the createList() function.

Related

For loop exceeds the limit when using img src

I have an img_urls array which contains 2 image urls.
I use this array to loop img tag and using for loop.
But instead of having 2 images, i have 3 images in my output.
This is my code;
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
So, whats is wrong with my code?
JSFIDDLE
When adding the first image you generate a new div.
Then the second image if appended to existing divs.
You should have only one destination div. Add an id to the main div:
<div id="container"></div>
--
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
You need to use selector i.e. id class in the main div as when the next iteration occurs it contains two div in the body. Check this fiddle
Problem is that you have $("div") as selector. So when you append the first image, you also add new div. So the next image is appended to two divs. Probably you can add id to your div, so
<div id="test"></div>
...
$("#test").append
Reason is you are appending everything inside the loop.
$(function() {
var img_urls = ["url1", "url2"];
var html= ""
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>";
}
$("div").append(html);
});
You are appending to global div element, you are appending div also, so generated html will append to generated div too.
Here is html,
<div class='test'></div>
Here is javascript code,
$(function() {
var img_urls = ["image_url1", "image_url2"];
var html = '';
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>"
}
$("div.test").append(html);
});
Please find here working link here
I hope this will help
<div id="container"></div>
for (var i = 0; i < img_urls.length; i++) {
console.log(img_urls.length)
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
when you append the first image you create a div in that div the horse is added and the first div is also populated by the horse
Try this and see Demo
<div></div>
$(function() {
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<img src=' " + img_urls[i] + "'/> </br>"
);
}
});

Get same CSS property value of 64 classes with pure Js or jquery

I have created 64 color buttons in dom by js. they have class name like this:
c1
c2
c3
c4
and so on..
I have created this by this codes:
var eg_color_ul_1 = $('.eg-ul-1');
var eg_color_ul_2 = $('.eg-ul-2');
for (var linum = 1; linum < 65; linum++) {
var Cselector = ".c" + linum;
var colorMenu = $(Cselector).css( "background-color" );
eg_color_ul_1.append("<a class=\"c" + linum + "\" color-code=\""+ colorMenu +"\"></a>"),
eg_color_ul_2.append("<a class=\"c" + linum + "\" color-code=\""+ colorMenu +"\"></a>");
}
I have already set all color in css style sheet.
like this:
.c1 {
background-color: #F44336;
}
.c2 {
background-color: #E91E63;
}
.c3 {
background-color: #9C27B0;
}
.c4 {
background-color: #673AB7;
}
Now i dont get the color in dom.
it show color-code="undefined"
How can I fix it?
I am sorry for the title. I can't understand what should be the title. So I put this.
Edit:
Due to a answer from #Abdul I have corrected my js. But still it shows color-code="undefined". When I console log this it shows
rgb(244, 67, 54) main.js:10
63 undefined main.js:10
this line is wrong:
var colorMenu = $(Cselector).css( "background-color" );
should be:
var colorMenu = $('.' + Cselector).css( "background-color" );
OR keep your line but change this:
var Cselector = ".c" + linum;
^ notice the period
see this fiddle
I would also refactor your code:
https://jsfiddle.net/6551a0ku/2/
var eg_color_ul_1 = $('.eg-ul-1');
var eg_color_ul_2 = $('.eg-ul-2');
for (var linum = 1; linum < 5; linum++) {
var className = 'c' + linum;
var Cselector = '.' + className;
var colorMenu = $(Cselector).css( "background-color" );
eg_color_ul_1.append(getATag(className, colorMenu)),
eg_color_ul_2.append(getATag(className, colorMenu));
}
function getATag(className, colorMenu) {
var aTag = "<a class='"
+ className
+ "' color-code='"
+ colorMenu
+ "'>a</a>";
return aTag;
}
I think there is a misunderstanding of where jQuery will pull the background-color property from. The DOM/jQuery doesn't have a direct understanding of the CSS properties you set down until you associate them with a DOM element either in the actual DOM, or in a Document Fragment.
var eg_color_ul_1 = $('.eg-ul-1');
var eg_color_ul_2 = $('.eg-ul-2');
for (var linum = 1; linum < 65; linum++) {
var Cselector = ".c" + linum;
// the problem is here, at this point, there are no dom elements that match .cN so there is no value to return
var colorMenu = $(Cselector).css( "background-color" );
eg_color_ul_1.append("<a class=\"c" + linum + "\" color-code=\""+ colorMenu +"\"></a>"),
eg_color_ul_2.append("<a class=\"c" + linum + "\" color-code=\""+ colorMenu +"\"></a>");
}
You can fix this by appending the anchor tags to the DOM first and then assigning the color code attribute.
var eg_color_ul_1 = $('.eg-ul-1');
var eg_color_ul_2 = $('.eg-ul-2');
for (var linum = 1; linum < 65; linum++) {
eg_color_ul_1.append("<a class=\"c" + linum + "\"></a>"),
eg_color_ul_2.append("<a class=\"c" + linum + "\"></a>");
}
for (var linum = 1; linum < 65; linum++) {
var domElement = $(".c" + linum)
var colorMenu = domElement.css("background-color")
domElement.attr('color-code', colorMenu)
}
I am unfamiliar with JQuery but if element.css("property") is the equivalent of element.style.property then that's your problem, the style there is referring to the inline style attribute and, as you are using a stylesheet, this is returning nothing.
The solution is to instead use getComputedStyle(), like so:
var eg_color_ul_1=$(".eg-ul-1");
var eg_color_ul_2=$(".eg-ul-2");
for(var linum=1;linum<65;linum++){
var colorMenu=window.getComputedStyle($(".c"+linum),null).getPropertyValue("background-color");
eg_color_ul_1.append("<a class=\"c"+linum+"\" data-color-code=\""+colorMenu+"\"></a>");
eg_color_ul_2.append("<a class=\"c"+linum+"\" data-color-code=\""+colorMenu+"\"></a>");
}
I'd also suggest using data attributes rather than custom attributes to avoid any potential issues.

No input text value via JavaScript DOM

I use JavaScript to create input text fields. And everything works fine, except attribute value. It simply doesn't generate and I don't know why?
Here's my code:
k=1;
function addtxt() {
var tip = document.createElement("input");
tip.type = "text";
tip.name = "tip[" + k + "]";
tip.value = "Question1";
var div = document.createElement("div");
div.innerHTML = "Question: " + tip.outerHTML + "<br />";
document.getElementById("mydiv").appendChild(div);
k++
}
This is what I got:
<input type="text" name="tip[1]">
may be try using setAttribute(), like, change:
tip.value = "Question1";
to
tip.setAttribute('value', "Question1");

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

How to dynamically assign an id to an image

var intFields = 0;
var maxFields = 10;
function addElement() {
"use strict";
var i, intVal, contentID, newTBDiv, message = null;
intVal = document.getElementById('add').value;
contentID = document.getElementById('content');
message = document.getElementById('message');
if (intFields !== 0) {
for (i = 1; i <= intFields; i++) {
contentID.removeChild(document.getElementById('strText' + i));
}
intFields = 0;
}
if (intVal <= maxFields) {
for (i = 1; i <= intVal; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Successfully added " + intFields + " fields.";
}
} else {
for (i = 1; i <= maxFields; i++) {
intFields = i;
newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intFields);
newTBDiv.innerHTML = "<input placeholder='recipient" + intFields + "#email.com' type='text' name='" + intFields + "'/><a href='javascript:removeElement();'><img id='strImg + " + intFields + "' src='images/minus.png' alt='Add A Field'/></a><input type='text' value='" + newTBDiv.id + "'/>";
contentID.appendChild(newTBDiv);
message.innerHTML = "Unable to create more than 10 receipient fields!";
}
}
}
My script here dynamically adds up to 10 fields where users will be able to enter an email address and to the right of the text box i add an image of a minus sign that calls another script. I'm having trouble working out how to assign and keep track of the minus signs. I need to be able to have the minus sign script's recognize the text box it is by and remove it. I can write the remove script easily enough but I'm unsure of how to tell the image which text box to remove. Any help, suggestions, or comments are greatly appreciated.
Thanks,
Nick S.
You can add a class to the field called minus and then check through like that. I would suggest using jquery for this.
To add the class
$("#element").addClass("minus");
To remove all elements with that class
$("body input").each(function (i) {
if($(this).attr("class") == "minus"){
$(this).remove();
}
});
The two best options, imo, would be 1) DOM-traversal, or 2) manipulating ID fragments.
Under the first way, you would pass a reference to the element where the event takes place (the minus sign) and then navigate the DOM from there to the get the appropriate text box (in jQuery you could use $(this).prev(), for example).
Under the second way, you would assign a prefix or a suffix to the ID of the triggering element (the minus sign), and the same prefix or suffix to the target element (the text box). You can then (again) generate the appropriate ID for your target element by simple string manipulation of the ID from the triggering element.
Is that sufficient to get you started?
Try adding a class to the field and the same class to the minus sign.
So add this right after the setAttribute id,
newTBDiv.setAttribute('class', 'field' + intFields);
then just remove any elements that have that class.

Categories