JQUERY - Building HTML with list variable - javascript

how to create Building HTML with list variable...
this my code error...
html
<div class="demo">
<!-- append code -->
</div>
css
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
jQuery code
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
html = $('<button class="demo_btn_' + cls + '"><span>' + txt + '</span></button>');
$(".demo").append(html);
});
and this output my code
<div class="demo">
<button class="demo_btn_btn1,btn2,btn3">
<span>button1,button2,button3</span></button>
</div>
And i want this...
<div class="demo">
<button class="demo_btn_btn1"><span>Button1</span></button>
<button class="demo_btn_btn2"><span>Button2</span></button>
<button class="demo_btn_btn3"><span>Button3</span></button>
</div>
Please help me, thank you in advance

The thing is, you're putting all the content together into a single button, which is why it's showing up as a single element.
You need to loop over the things and assign each element like below.
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
for (let i = 0; i < 3; i++)
{
html = $('<button class="demo_btn_' + cls[i] + '">' + txt[i] + '</button>');
$(".demo").append(html);
}
});
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
</div>

In order to do what you want, you would have to loop through the array one at a time, so what you can do is:
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
for (var i = 0; i < 3; i++) {
$(".demo").append(
$('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>')
);
}
});

You can simply use .each() to loop through array .. and += to html then use .html() after loop
$(function(){
var html = '';
cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
$.each(cls , function(i){
html += '<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>';
});
$(".demo").html(html);
});
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
<!-- append code -->
</div>

Try using a loop, and create new html elements based on the index of cls and txt. Posting from my phone, so apologies if the formatting is messed up.
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
for (var i =0; i < cls.length; i++){
var html = $('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i]+ '</span></button>');
$(".demo").append(html);
}
});

I would use for loop for this case.
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
for (var i = 0; i < cls.length; i++) {
$(".demo").append('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>');
}
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
<!-- append code -->
</div>

Related

How to avoid this duplication of code? I wanted to repeat the same code 25 times

I didn't want to repeat the same code 25 times in the part of "getElementById", "carregaItem(iVid)" and " < div id="item"> < /div> ". The BDVYT array has 25 elements I just put 2 for simplicity. There must be some way to do it but I'm not getting there.
var BDVYT = [{durac:27},{durac:23},];
refItem = document.getElementById("item");
refItem2 = document.getElementById("item2");
function inic(){
mostraItem();
}
function mostraItem(){
carregaItem(0);
carregaItem1(1);
//-----------
//until carregaItem24(24)
}
function carregaItem(iVid){
var codHTML = "";
codHTML += '<div id="itemInfo">';
codHTML += 'duração: <b>' + duracVid(iVid) + 'minutos</b>';
codHTML += '</div>';
refItem.innerHTML = codHTML;
}
function carregaItem1(iVid){
var codHTML = "";
codHTML += '<div id="itemInfo2">';
codHTML += 'duração: <b>' + duracVid(iVid) + 'minutos</b>';
codHTML += '</div>';
refItem2.innerHTML = codHTML;
}
//until carregaItem24(iVid)
function duracVid(iVid){
return BDVYT[iVid].durac;
}
<body onload="inic()">
<div id="item"></div>
<div id="item2"></div>
</body>
Use classes for the refItems instead, and when iterating over the collection of them, use the index being iterated over to find the associated element in the BDVYT array.
var BDVYT = [{durac:27},{durac:23},];
const refItems = document.querySelectorAll('.item');
refItems.forEach((item, i) => {
item.innerHTML = `
<div id="itemInfo2">
duração: <b>${BDVYT[i].durac} minutos</b>
</div>
`;
});
<body>
<div class="item"></div>
<div class="item"></div>
</body>

HTML - JavaScript - Adding and Deleting/Hiding Elements

In my website the user is going to select an image, that image will then be inserted into a div tag. I need it so when the user clicks the image that was inserted into the div then it will be removed (deleted or hidden) from the div. I've tried:
document.getElementById("elementId").style.display = "none";
and other similar things. I really just cant get this to work please help!
HTML + JavaScript code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
var addCard = function(cardName)
{
if("undefined" != document.getElementById("card" + cardNumber).value)
{
if(deck.indexOf(cardName) > -1)
{
}
else
{
if(deck.length != 1)
{
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if(deck.length >= 1)
{
cardNumber = 1;
}
}
}
}
</script>
</head>
<body>
<div id = "card1" class = "cards"></div>
<div id = "1">
<img class = "cardSize" onclick = "addCard('Archer')" src = "Images/Cards/Archer.png">
</div>
</body>
CSS Code:
.cards
{
height:150px;
width:125px;
float:left;
margin-left:6.2%;
margin-bottom:30px;
border:5px solid #ff6666;
background-color:#ff6666;
}
.cardSize
{
height:150px;
width:125px;
float:left;
margin-left:7%;
margin-top:30px;
}
You can delete the img by id.
Also fix the issue with the updateCards function:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = "updateCards(\'' + cardName + '\')" src = "' + cardName + '.png">';
For example,
<div id="card1" class="cards">
<img id="Archer" class="deckCardSize" onclick="updateCards('Archer')" src="Archer.png">
</div>
Then just remove the div with id="Archer":
document.getElementById("Archer").remove();
FYI, I added a simple updateCards function that just hides the img instead of removing it entirely :
var updateCards = function(cardName) {
document.getElementById(cardName).style.display = 'none';
}
You need to attach a click event listener to a class that is applied to all inserted images. the function that the listener fires would then apply css.style.display = "none" to this
First, remove all spaces between attributes and its values (I mean everywhere in your code), that is:
<div id="card1" class="cards"></div><!-- correct -->
<div id = "card1" class = "cards"></div><!-- incorrect -->
Second, you have an error in your code here:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
You have missed double quotes around onclick's value. Replace it with this:
document.getElementById("card" + cardNumber).innerHTML = '<img id="' + cardName + '" class="deckCardSize" onclick="updateCards(' + cardName + ')" src="Images/Cards/' + cardName + '.png">';
Also, you have to define function updateCards(name), it maybe empty, but it must exists. If it doesn't exists, than any javascript code will stops running after you clicked on that image.
Third, <div id = "1"> has an error too. id attribute must starts from a letter.
here is working code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
function addCard(cardName) {
if ("undefined" != document.getElementById("card" + cardNumber).value) {
if (deck.indexOf(cardName) > -1) {
} else {
if (deck.length != 1) {
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id="img' + cardName + '" class="deckCardSize" onclick="updateCards(\'' + cardName + '\')" src="Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if (deck.length >= 1) {
cardNumber = 1;
}
}
}
}
function updateCards(cardName) {
//some work
document.getElementById("img" + cardName).remove();
}
</script>
</head>
<body>
<div id="card1" class="cards"></div>
<div id="main1">
<img class="cardSize" onclick="addCard('Archer')" src="Images/Cards/Archer.png">
</div>
</body>
Tested and worked!

The right use of jQuery? Owl carousel

For my project I use the OwlCarousel. http://www.owlgraphic.com/owlcarousel/#more-demos
I managed to get 3 carousels on my page. But I think the page is getting to slow. Is there a possibility that I make to many steps?
Actually I don't need to read the json file because I store it in the localStorage one page before. But I didn't know how to delete it out without corrupting the code.
So the main question is how to make just one jQuery call to fill all 3 carousels?
This is the code I use to call the carousel:
<div id="dodatni1" style="visibility:hidden" >
<div id="owl-demo" class="owl-carousel" ></div>
</div>
<div id="dodatni2" style="visibility:hidden" >
<div id="owl-demo2" class="owl-carousel" ></div>
</div>
<div id="dodatni3" style="visibility:hidden" >
<div id="owl-demo3" class="owl-carousel" ></div>
</div>
And this is the carousel code:
$(document).ready(function() {
$("#owl-demo").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg ="http://www.spleticna.si/images/"+localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3239){
content += "<a href=\"produkt.html?id=" + j + "&slider=a\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo").html(content);
}
});
$(document).ready(function() {
$("#owl-demo2").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 2615){
content += "<a href=\"produkt.html?id=" + j + "&slider=b\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo2").html(content);
}
});
$(document).ready(function() {
$("#owl-demo3").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});
I'm not sure how much speed you could get but you can rewrite your JS:
$(document).ready(function(){
//Assuming they all use the same data source/settings?
$("#owl-demo3,#owl-demo2,#owl-demo1").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});

Appending to a tag

I want to append data I fetched from server to a div tag, but I can't get it to work. That's HTML with a div tag to which I'd like to append data from the JS code.
HTML:
<body onload="initialize()">
<div id="text"></div>
</body>
And here is JavaScript code. I would like to replace document.write with a function that will append data to a div tag.
JS:
function initialize() {
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
document.write('<img src="' + data[i].image + '" />' + data[i].title + data[i].description + '<br>');
}
});
}
Fiddle: http://jsfiddle.net/GDxtf/
I just started learning JavaScript. Help will be greatly appreciated :)
Paste this code in the bottom of your HTML document, right before </body>:
<script>
// If you're not using an HTML5 doctype, use <script type="text/javascript> instead of just <script>
$(function () {
$targetDiv = $("#text");
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
var $div = $("<div />");
var $img = $("<img />");
$img.attr("src", data[i].image);
$img.appendTo($div);
var $title = $("<h2>" + data[i].title + "</h2>");
$title.appendTo($div);
var $description = $("<p>" + data[i].description + "</p>");
$description.appendTo($div);
$div.appendTo($targetDiv);
}
});
});
</script>
Did this solve your problem?

Javascript not writing to HTML definition list

Can anyone help me with why this JavaScript is not writing to the definition list in the body? When I debug, the object is there and the lines are all executed. Also, if I use document.write the information will overwrite the page. I'm just having trouble with adding this HTML to the predefined definition list. There are no errors in the console. Any help is appreciated.
Javascript in head
function writeGph(obj, chartNum) {
var data = obj;
for (i = 0; i < obj.tab1.length; i++) { //Loop to create each column of the graph
document.getElementById(chartNum).innerhtml += '<dt>' + data.tab1[i].name + '</dt>'
document.getElementById(chartNum).innerhtml += '<dd class="p100"><span><b>' + data.tab1[i].top + '</b></span></dd>'
document.getElementById(chartNum).innerhtml += '<dd class="sub p' + data.tab1[i].bot + '"><span><b>' + data.tab1[i].bot + '</b></span></dd>';
console.log(data.tab1[i].top);
}
}
function writeAxis(obj, axisNum) {
for (i = 0; i < obj.tab1.length; i++) { //Loop to create each x-axis label
document.getElementById(axisNum).innerhtml += '<li>' + obj.tab1[i].name + '</li>';
}
}
function writeTable(obj, tableNum) {
document.getElementById(tableNum).innerhtml += '<tr><th>Business</th><th>Number</th><th>Percent</th></tr>';
for (i = 0; i < obj.tab1.length; i++) { //Loop to fill in table information
obj.tab1[i].botl = Math.round(10000 * (obj.tab1[i].num / obj.tab1[i].all)) / 100;
document.getElementById(tableNum).innerhtml += '<tr><td>' + obj.tab1[i].name + '</td><td>' + obj.tab1[i].num + '</td><td>' + obj.tab1[i].botl + '%</td></tr>';
}
}
HTML in body
<dl class="chart" id="chart1"></dl>
<ul class="xAxis" id="xAxis1"></ul>
<table id="table1"></table>
It's not .innerhtml, it's .innerHTML

Categories