JavaScript function is not sending variable - javascript

function ispisProizvoda(nizProizvoda){
// console.log(nizProizvoda)
let html = "";
let divIspis = document.querySelector("#ispis-proizvoda");
if(nizProizvoda.length == 0){
html = `<div class="row">
<div class="col-12">
<p class="alert alert-danger">Trenutno nema proizvoda.</p>
</div>
</div>`;
}
else{
for(let objProizvod of nizProizvoda){
html += `<div class="row my-3 border">
<div class="col-4">
<img src="${objProizvod.slika}" alt="${objProizvod.naziv}" />
</div>
<div class="col-8">
<h2>${objProizvod.naziv}</h2>
<p>${ispisNaziva(objProizvod.kategorijaID, kategorije)}</p>
<p class="alert alert-primary">${ispisNaziva(objProizvod.brendID, brendovi)}</p>
<hr />
${ispisDostave(objProizvod.besplatnaDostava)}
<div class="popust">
<div class="cena">
**${shipping(objProizvod.price)}**
</div>
</div>
<div class="specifikacije pt-4">
<p>Specifikacije</p>
<ul>
</ul>
</div>
</div>
</div>`
}
}
divIspis.innerHTML = html;
}
function shipping(getPrice){
let html = "";
if(dostava){
html = `<p class="alert alert-success">Besplatna dostava</p>`;
}
else{
html = `<p class="alert alert-danger">Nema besplatne dostave</p>`;
}
return html;
}
I have a problem, function call shipping() is not senind any data, if I console log getPrice in function it says it is undefined, I tested varable in function call and has value, so that is not the problem.I used ajax to fetch data and data is stored in local storage, I don't know why this function is not working. Other functions are working. Is it beacuse I called function before it is declared?

Related

how to make the button click executes code only one time

I want the button with the id #show-text-area execute the postButton(); function only once so it won't create a second elements whenever clicked (i want it to create it for only one time and won't work again until clicked another button).
Hope my question was clear enough.
HTML
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button onclick="postButton();">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
Javascript
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
}
You could disable the button after activation, this has the benefit of informing the user that further clicks won't do anything.
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
Otherwise you could simply have the function short-circuit if it has already been called.
// alreadyPosted is scoped outside of the function so it will retain its value
// across calls to postButton()
let alreadyPosted = false;
let postButton = function() {
// do nothing if this isn't the first call
if (alreadyPosted) { return; }
// mark the function as called
alreadyPosted = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
The following works.
let postButton = function(event) {
event.target.disabled = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
};
document.getElementById('post').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button>Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
You can also use hide show function on textarea if you do not want to create one.
let postButton = function() {
let d = document.getElementById('post_data').style.display;
if(d=='none'){
document.getElementById('post_data').style.display = 'block';
}
}
document.getElementById('post_data').style.display = 'none';
document.getElementById('post_btn').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post">
<button id="post_btn">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
<textarea class="post-data" id="post_data" placeholder="Text (optional)"></textarea>
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>

How do I check if a div contains another div?

I need to show alert if my parent div has a child div using JavaScript only No jQuery.
I have tried using the contains() function to check my div and send alert but it's not working.
<script type="text/javascript">
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else
{
alert("no");
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
There should be an alert box with message yes in it but it's not visible. I have also tried checking JavaScript using the alert() method only without any code.
Your code is running before the DOM is fully loaded. Move your script at the bottom of the page:
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
<script type="text/javascript">
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
}
else{
alert("no");
}
</script>
OR: Wrap the code with DOMContentLoaded which will ensure that code placed inside will be executed only after the DOM is fully loaded:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
}
else{
alert("no");
}
});
</script>
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
You can use querySelector . If the child is not present it will give a null value
var hasChildDiv = document.getElementById("commentBox").querySelector("#comment1");
if (hasChildDiv !== null) {
alert('yes')
}
<script type="text/javascript">
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
let table = document.getElementById("niceTable");
let tds = table.getElementsByTagName("td");
for (let i = 0; i < tds.length; i++) {
tds[i].onclick = function () {
checkInputElement(tds[i]);
};
}
function checkInputElement(element) {
let input = element.querySelector("input");
console.log(element.contains(input));
}
Make sure that the whole DOM is loaded before you execute javascript code.
You can do this by adding the event listener DOMContentLoaded to your code or placing your scripts at the end of the file
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv && parentDiv.contains(childDiv)) {
alert("yes");
}
else {
alert("no");
}
}, false);
</script>
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
You won't get an alert because parentDiv will not exist yet and the value will be null. This results that it does not contain the contains() function and it will throw an error. To be safe you can add a null check inside the if statement.
How about using window.onload function?
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
This will execute the function until dom loads completely
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>

Javascript Function back to it's original place

I'm not actually a programmer but I have to do this website work properly. And for that I'll need your help.
I'm messing with some javascript and I manage to maek this:
<script>
function funcaosabores1() {
document.getElementById("testeagora1").innerHTML = "";
document.getElementById('contento1').style.visibility="visible";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores2() {
document.getElementById("testeagora2").innerHTML = "";
document.getElementById('contento2').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores3() {
document.getElementById("testeagora3").innerHTML = "";
document.getElementById('contento3').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores4() {
document.getElementById("testeagora4").innerHTML = "";
document.getElementById('contento4').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores5() {
document.getElementById("testeagora5").innerHTML = "";
document.getElementById('contento5').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
}
</script>
And I can't find on how to make for example: funcaosabores1 is clicked and is now visible, when I click funcaosabores2, the first one is hidden and the second is showing. But I can't click on the first one back because it was already clicked. (Idk if it's called return)
This is the div's called in the script:
<div class="animacao_saborgingerale" id="contento2" style="visibility:hidden;"></div>
<div class="animacao_saboruvasyrah" id="contento3" style="visibility:hidden;"></div>
<div class="animacao_sabortangerina" id="contento4" style="visibility:hidden;"></div>
<div class="animacao_saboruvabranca" id="contento5" style="visibility:hidden;"></div>
<div class="sabor-melancia"><p onclick="funcaosabores1()" id="testeagora1">MELANCIA</p> </div>
<div class="sabor-gingerale"><p onclick="funcaosabores2()" id="testeagora2">GINGER ALE</p></div>
<div class="sabor-uvasyrah"><p onclick="funcaosabores3()" id="testeagora3">UVA SYRAH</p></div>
<div class="sabor-tangerina"><p onclick="funcaosabores4()" id="testeagora4">TANGERINA</p></div>
<div class="sabor-uvabranca"><p onclick="funcaosabores5()" id="testeagora5">UVA BRANCA</p></div>
This seems quite messy but I'm here if you guys can help me! Thanks.
The CodePen of how it is right now. #nielsdebruin
I think you just want to do something like this:
let prevButton;
let prevContent;
function toggle(e) {
if (prevButton) prevButton.style.visibility = 'visible';
prevButton = e.target;
e.target.style.visibility = 'hidden';
let id = e.target.id;
let number = id.slice(-1);
if (prevContent) prevContent.style.visibility = 'hidden';
prevContent = document.getElementById('contento' + number);
prevContent.style.visibility = 'visible';
}
<div class="content animacao_saborgingerale" id="contento1" style="visibility:hidden;">1</div>
<div class="content animacao_saborgingerale" id="contento2" style="visibility:hidden;">2</div>
<div class="content animacao_saboruvasyrah" id="contento3" style="visibility:hidden;">3</div>
<div class="content animacao_sabortangerina" id="contento4" style="visibility:hidden;">4</div>
<div class="content animacao_saboruvabranca" id="contento5" style="visibility:hidden;">5</div>
<div class="button sabor-melancia"><p onclick="toggle(event)" id="testeagora1">MELANCIA</p> </div>
<div class="button sabor-gingerale"><p onclick="toggle(event)" id="testeagora2">GINGER ALE</p></div>
<div class="button sabor-uvasyrah"><p onclick="toggle(event)" id="testeagora3">UVA SYRAH</p></div>
<div class="button sabor-tangerina"><p onclick="toggle(event)" id="testeagora4">TANGERINA</p></div>
<div class="button sabor-uvabranca"><p onclick="toggle(event)" id="testeagora5">UVA BRANCA</p></div>

Retrieving data from api using ajax/vanilla javascript

Good day everyone please am trying to create a movie project using just javacript and ajax without fetch,jquery etc, i have a bug, if i enter a word in the inputbox and submit to retrieve an array of movies from the api for the first time it works but if i try searching for other movies again it doesn't work accept i reload the page. please doee anyone have a solution to this bug? thanks
document.getElementById("searchForm").addEventListener("submit", loadMovies);
function loadMovies(e) {
let input = document.getElementById("searchText");
const xhr = new XMLHttpRequest();
xhr.open("GET", `https://api.themoviedb.org/3/search/movie?api_key=b94d8dbb7dcd23af16414e00a058c9ad&language=en-US&query=${input.value}`, true);
xhr.onload = function() {
if (this.status === 200) {
let movies = document.getElementById("movies");
let res = JSON.parse(this.responseText);
res.results.forEach(function(movie) {
movies.innerHTML += `
<div class="col-md-3">
<div class="card bg-dark">
<div class="card-block">
<img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" class="img-fluid">
<h4>${movie.title}</h4>
Movie Details
</div>
</div>
</div>
`;
});
} else {
console.log("Movie not found");
}
}
xhr.send();
e.preventDefault();
}
<div class="container mt-5">
<div class="jumbotron bg-dark">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movie....">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
I didn't realize there was many results you wanted to display. In that case use += off course and just empty the result beforehand movies.innerHTML = ''
document.getElementById("searchForm").addEventListener("submit", loadMovies);
function loadMovies(e) {
let input = document.getElementById("searchText");
const xhr = new XMLHttpRequest();
xhr.open("GET", `https://api.themoviedb.org/3/search/movie?api_key=b94d8dbb7dcd23af16414e00a058c9ad&language=en-US&query=${input.value}`, true);
xhr.onload = function() {
if (this.status === 200) {
let movies = document.getElementById("movies");
let res = JSON.parse(this.responseText);
movies.innerHTML = '';
res.results.forEach(function(movie) {
movies.innerHTML += `
<div class="col-md-3">
<div class="card bg-dark">
<div class="card-block">
<img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" class="img-fluid">
<h4>${movie.title}</h4>
Movie Details
</div>
</div>
</div>
`;
});
} else {
console.log("Movie not found");
}
}
xhr.send();
e.preventDefault();
}
<div class="container mt-5">
<div class="jumbotron bg-dark">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movie....">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>

How can I get specific information from an external api to my ng-repeat

main.html
<div class="row" ng-repeat="post in myBlogPosts.slice().reverse()">
<br>
<div class="col-md-9 text-center">
<a href="#/blog-post/{{post._id}}">
<div class="thumbnail mTextBg customShadow">
<br>
<img class="img-responsive" src="http://placekitten.com/700/400" alt="">
<div class="caption">
<h3>{{post.imdbId}}</h3>
<p>{{post.blogContent}}</p>
</div>
</div>
</a>
</div>
<div class="col-md-3">
// I WANT THIS PART !!
<div class="well sideBars customShadow">
<img class="img-responsive" ng-src="{{film.Poster}}" title="{{film.Title}}">
<h4 class="text-center">{{film.Title}}</h4>
<p class="text-center" style="margin-bottom: 2px;"><b>Year:</b> {{film.Year}}</p>
<p class="text-center"><span class="customMargin">Runtime: {{film.Runtime}}</span></p>
<p class="text-center"><span class="customMargin">Director: {{film.Director}}</span></p>
<p class="text-center"><span class="customMargin">Writer: {{film.Writer}}</span></p>
<p class="text-center"><span class="customMargin">Actors: {{film.Actors}}</span></p>
</div>
</div>
</div>
This is part of my main.html . In h3 and p tags, I get imdbId and blogContent from my database and put it in ng-repeat in order to traverse blog posts in list. I want to be able get other information(under // I WANT THIS PART) for every post in myBlogPost.
MainController.js
var refresh = function() {
$http.get('/myDatabase').success(function(response) {
$scope.myBlogPosts = response;
});
};
refresh();
This part work as expected when page loaded.
I need also these parts in Main Controller ;
var onGetFilmData = function (data) {
$scope.film = data;
};
var onError = function (reason) {
$scope.error = reason;
};
imdb.getImdbInfo(-- need Id --).then(onGetFilmData, onError);
But I need to put each post id somehow in order to get specific data from Imdb api.
Imdb.js
(function(){
var imdb = function($http){
var getImdbInfo = function (id) {
return $http.get('http://www.omdbapi.com/?i=' + id + '&plot=short&r=json')
.then(function(response){
return response.data;
});
};
return{
getImdbInfo: getImdbInfo
};
};
var module = angular.module('myApp');
module.factory('imdb', imdb);
})();
If I delete id part and put a specific id string in getImdbInfo function, all post in main.html fill with just one film information. I want to fetch those data for each film in my database(I am holding imdb id of each film in my database).
MainController
var jsonObj = {};
var refresh = function() {
$http.get('/myDatabase').success(function(response) {
jsonObj = response;
for(var i = 0; i < jsonObj.length ; i++){
jsonObj[i].title = '';
}
for(var i = 0; i < jsonObj.length ; i++){
(function(i) {
imdb.getImdbInfo(jsonObj[i].imdbId).then(function (data) {
jsonObj[i].title = data.Title;
});
})(i);
}
$scope.myBlogPosts = jsonObj;
});
};
refresh();
main.html
<div class="row" ng-repeat="post in myBlogPosts.slice().reverse()">
<br>
<div class="col-md-9 text-center">
<a href="#/blog-post/{{post._id}}">
<div class="thumbnail mTextBg customShadow">
<br>
<img class="img-responsive" src="http://placekitten.com/700/400" alt="">
<div class="caption">
<h3>{{post.imdbId}}</h3>
<p>{{post.blogContent}}</p>
</div>
</div>
</a>
</div>
<div class="col-md-3">
<!-- Side Widget Well -->
<div class="well sideBars customShadow">
<h4 class="text-center">{{post.title}}</h4>
</div>
</div>
</div>
I solve my problem with adding response from Imdb to my json object which is coming from database. So I can easily use them in ng-repeat.

Categories