print array with js and add html with jQuery - javascript

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.

HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/

Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});

First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);

It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

Related

How to convert html to variable in javascript?

I have problem while convert html to javascript variable.
My HTML Code
<div onclick="openfullanswer('2','Discription part','This is the code part');">
I want to create this html code dynamically, but I have the problem in quote(" and ')
I tried like below
for(i=0;i<result.length;i++)
{
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
}
https://jsfiddle.net/8782n60z/1/
Way 1:
You should have to change the sequence of single and double quotes and have to escape the single quotes with '\' in on-click function arguments
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +='<div onclick="openfullanswer(\''+result[i].ReplyID+'\',\''+result[i].Description+'\',\''+result[i].Code+'\');">Test code</div>';
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
Way 2:
Don't change the sequence of quotes.
Only change the onclick event declaration quotes from signle to double and escape double quotes with '\' and you need not have to change anything.
Please check the below snippet for more understanding.
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
strVar="";
for(i=0;i<result.length;i++)
{
strVar +="<div onclick=\"openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
}
document.getElementById("test").innerHTML=strVar;
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
strVar +="<div onclick=\"openfullanswer('"+result[i].ReplyID+"','"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
try this.
The code you wrote produces the following:
<div onclick='openfullanswer(1,'This is my description','This is my Code Part');'>Test code</div>
The above is not valid since there are single quotes inside the value of onclick.
You will need to escape these characters.
strVar +="<div onclick=\"window.openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');\">Test code</div>";
See here an article in SO explaining this matter in detail.
See a working demo here: https://jsfiddle.net/8782n60z/3/
P.S. I changed a bit the way to declare and call the function because it gave an error.
You can use template literal
var result = [];
var obj = new Object();
obj.ReplyID = 1;
obj.Description = "This is my description";
obj.Code = "This is my Code Part";
result.push(obj);
strVar = "";
for (i = 0; i < result.length; i++) {
strVar += `<div
onclick="openfullanswer('${result[i].ReplyID}'
, '${result[i].Description}'
, '${result[i].Code}');">
Test code
</div>`;
}
function openfullanswer(replyid, desc, code) {
alert("success");
console.log(replyid, desc, code);
}
document.getElementById("test").innerHTML = strVar;
<div id="test">
</div>
jsfiddle https://jsfiddle.net/8782n60z/5/
Instead of building the string you could also use document.createElement to generate your div. And then append it to the parent #test
var result=[];
var obj=new Object();
obj.ReplyID=1;
obj.Description="This is my description";
obj.Code="This is my Code Part";
result.push(obj);
var div;
for(i=0;i<result.length;i++)
{
div = document.createElement('div');
div.innerHTML = 'Test code'
div.onclick = openfullanswer;
}
document.getElementById("test").appendChild(div);
function openfullanswer(replyid,desc,code)
{
alert("success");
}
<div id="test">
</div>
Since what you need has already been answered above, I'll just add that the way you are trying to access and manipulate DOM element is not safe or recommended way of handling dom elements. Instead of directly writing to DOM, its better to make use of addEventListner() function and bind your element to it.
For instance, instead of writing ,
strVar +="<div onclick='openfullanswer("+result[i].ReplyID+",'"+result[i].Description+"','"+result[i].Code+"');'>Test code</div>";
you should be instead doing
strVar.outerHTML += '<input id="btncall" ...>'
document.getElementById ("btncall").addEventListener ("click", openfullanswer(parameters), false);

Count html elements in ajax returned data

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!
Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});
$('.blah','context').length
Replace context by object in which you want to search

Output html tag as text into a div, each array element on separate line

I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>

Is it possible to use a for loop in <select> in html? and how?

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/

How to display images using Javascript and JSON

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

Categories