Jquery How To Stop Append from Appending Previous Element - javascript

I'm having trouble to display the star of each hotel and not sure on how to do it. I have like 5 hotels, and each has different value of hotelStar.
My Javascript code:
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img;
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
$(parent).append('<img src="image/hotelstar.png" class="hotelStar" />')
}
}
And my HTML Code is:
<h1>Hotel 1</h1>
<p class="star"><script>
hotelStar = 4;
GetStarHotel();
</script></p>
<h1>Hotel 2</h1>
<p class="star"><script>
hotelStar = 3;
GetStarHotel();
</script></p>
<h1>Hotel 3</h1>
<p class="star"><script>
hotelStar = 2;
GetStarHotel();
</script></p>
It is adding my previous Hotel's Stars. How can I prevent it from adding the same element?

Instead of append() you can use .html(), check updated code below
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img,
star = '';
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
star += '<img src="'+imagePath +'" class="hotelStar" />';
}
$(parent).html(star)
}
i have simplified your code. check updated snippet below
$('p.star').each(function(){
count = $(this).data('star'),
star = '',
imagePath = 'http://www.freeiconspng.com/uploads/download-png-image-star-png-image-1.png';
for (var i = 0; i < count; i++) {
star += '<img src="'+imagePath +'" width="16" class="hotelStar" alt="'+i+'" />';
}
$(this).html(star)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hotel 1</h1>
<p class="star" data-star ="4" ></p>
<h1>Hotel 2</h1>
<p class="star" data-star ="3"></p>
<h1>Hotel 3</h1>
<p class="star" data-star ="2"></p>

Related

Script code will display when click button

I'm trying to make a very, very simple image slider/slideshow with no autoplay. I only want to go to next or prev image on click. Having some issues as you can read below.
Problem : everytime I will click previous button it will display my javascript code
var backgroundImage = new Array();
backgroundImage[0] = "images/image1.jpg";
backgroundImage[1] = "images/image2.jpg";
backgroundImage[2] = "images/image3.jpg";
backgroundImage[3] = "images/image4.jpg";
backgroundImage[4] = "images/image5.jpg";
backgroundImage[5] = "images/image6.jpg";
backgroundImage[6] = "images/image7.jpg";
function displayAllImages() {
var i = 0,
len = backgroundImage.length;
for (; i < backgroundImage.length; i++) {
var img = new Image();
img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
document.getElementById('images').appendChild(img);
}
};
displayAllImages();
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function() {
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
} else {
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function() {
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
} else {
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" align="center">
<div id="slider-wrapper">
<div id="slider">
<div class="backgoundImage">
<ul id="images"></ul>
</div>
</div>
</div>
</div>
<div id="container">
<hr>
<div id="nav" align="center">
<div id="button-previous">
<input id="prev_btn" type="button" name="prev_btn" value="Previous">
</div>
<div id="button-next">
<input id="next_btn" type="button" name="next_btn" value="Next">
</div>
</div>
in this case, I want to ask if how can I add div tag with a class=sp and inside of it is the img tag.
Use image.src instead of image.url and to add image in div, First create div, set attribute you want and append image in div
var div = document.createElement('div');
div.setAttribute('class', 'sp');
var img = new Image();
img.src = backgroundImage[i]; // img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
div.appendChild(img); // Append Image in Div
After that use
document.getElementById('images').appendChild(div);
Or use like that
$('#images').append('<div class="sp"><img src="' + backgroundImage[i] + '" width="160px" height="120px" /></div>');
The problem is here:
for (; i < backgroundImage.length; i++) {
var img = new Image();
img.url = backgroundImage[i];
img.style.width = '160px';
img.style.height = '120px';
// //document.getElementById('images').appendChild(img);
document.write("<div class=sp><img src='" + backgroundImage[i] + "' width='160' height='120'/></div>");
}
First: in your for loop i ssuggest initializing i inside the for loop (but is optional):
for (var i =0; i < backgroundImage.length; i++) {
Second: document.write(...);
The write() method will replace the whole content of your document. Besides, it's inside a for loop, then, you are replacing the whole document with every iteration.
You should use the other approach: appendChild(). appendChild doesn't overwrite your document, it just adds an element inside another.
Try with appendChild, if you have more questions, update your questions or post a comment.

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

How to display a number below each dynamically created images?

I want to display a particular image as many times as the number given by user.This part is accomplished. But i want to display a number below each image. For example if user input is 4, there should be 4 images with '1' below 1st image '2' below second. The image must also be clickable.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo">
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
}
</script>
</body>
</html>
var imageSrc = "http://fc08.deviantart.net/fs71/f/2010/148/1/9/20x20_PNG_Icons_DOMO_by_JMcIvor.png";
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var demo = document.getElementById("demo");
var container = document.createElement("div");
container.setAttribute("class", "container");
for(var i=0; i<x; i++) {
var image = document.createElement("img");
image.setAttribute("class", "image");
image.setAttribute("src", imageSrc);
container.appendChild(image);
var text = document.createElement("div");
text.innerHTML = i+1;
container.appendChild(text);
demo.appendChild(container);
}
}
#demo {
}
.container {
}
.image {
}
.text {
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo"></div>
</body>
</html>
I just use another image url to test the code, replace it with your one. I hope this helps.
You already have the number you're looking for in your loop. So you can simply add it to your array like this.
JS:
function imag() {
var x = document.getElementById("myNumber").value;
var c = "<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push("<div class='image'>" + c + "<br />" + (i+1) + "</div>");
}
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
CSS:
div.image {
display: inline-block;
}

Can't get child div IDs within each parent div/class

When I try to get child div IDs within each parent div/class I get the error "Uncaught TypeError: Cannot set property '0' of undefined". I am using this javascript with scriptaculous so I have turned off the "$" shortcut.
Example HTML:
<div id="group1" class="section">
<h3 class="handle"><input type="hidden" name="groupName1" value="MyGroup1">MyGroup1</h3>
<div id="item_73548" class="lineitem">item a</div>
<div id="item_73386" class="lineitem">item b</div>
<div id="item_73163" class="lineitem">item c</div>
</div>
<div id="group2" class="section">
<h3 class="handle"><input type="hidden" name="groupName2" value="MyGroup2">MyGroup2</h3>
<div id="item_73548" class="lineitem">item d</div>
<div id="item_73386" class="lineitem">item e</div>
<div id="item_73163" class="lineitem">item f</div>
</div>
The Javascript:
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);
The output should be:
groups[0][0]="item_73548";
groups[0][1]="item_73386";
groups[0][2]="item_73163";
groups[1][0]="item_73548";
groups[1][1]="item_73386";
groups[1][2]="item_73163";
Fiddle here: http://jsfiddle.net/qy9dB/3/
You just need to make sure that groups[i] is setup as an array before you try and add 2nd level elements to the array.
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
groups[i] = [];
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);

Select top 3 values from variable, then next 3 etc

I have this variable with images. I also have 3 div's in which I want to put the images.
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'
]
By using this code every div does get a random image, which is nice but not what I want. How can I use jQuery to put the first 3 images inside the 3 divs, then the second 3 images in the div?
$(".art").click(function(){
$(".art").each(function(){
$(this).find("img").remove();
$(this).prepend('<img src="assets/images/' + images[Math.floor(Math.random()*images.length)] + '">');
});
});
<div class="art">
<div class="art">
<div class="art">
Not sure what you mean, please elaborate if this is not what you are looking for..
http://jsfiddle.net/jFIT/c7U7q/1/
where the code is giving just text now, you can wrap that text in an <img src= /> to give you the images..
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'];
$(".art").click(function () {
$(this).html(getNext3()); //images[Math.floor(Math.random()*images.length)]);
});
$('#startLoop').click(function () {
loopImages();
});
function loopImages(){
var art = $('.art');
art.fadeOut(1000, function () {
art.html(getNext3()).fadeIn(1000, function() { loopImages(); });
});
}
var counter = 0;
function getNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs += ' ' + images[counter];
counter++;
}
return imgs;
}
UPDATED
(load 3 into 3 divs at a time.)
http://jsfiddle.net/jFIT/c7U7q/7/
function setNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs = images[counter];
console.log(imgs);
console.log(i);
$("div.art:nth-child(" + (i + 1) + ")").html(imgs);
console.log($("div.art:nth-child(" + i + ")"));
counter++;
}
}
You can keep track of the current image index and then add the number to increase the index by each click
html
<div class="art">
<img data-imageindex="0" src="" />
</div>
<div class="art">
<img data-imageindex="1" src="" />
</div>
<div class="art">
<img data-imageindex="2" src="" />
</div>
js
var artLength = $(".art").length;
$(".art").click(function () {
$(".art").each(function () {
var $image = $(this).find("img");
var nextImageIndex = $image.data("imageindex") + artLength;
if (nextImageIndex >= images.length) {
nextImageIndex -= images.length;
}
$image.data("imageindex", nextImageIndex).attr("src",
"assets/images/" + images[nextImageIndex]);
});
});
http://jsfiddle.net/44zB4/

Categories

Resources