Variable incrementation is not working - javascript

I have a button in HTML, and I want to increase a JavaScript variable value when clicked:
<a id="right-btn" onclick="increasePokemon_ID()">
Here is the script:
var pokemon_ID = 1;
function increasePokemon_ID() {
pokemon_ID++;
}
I also tried this way, but none of them worked:
document.getElementById("right-btn").onclick = function() {
increasePokemon_ID();
}
The value is outputted in this div:
document.getElementById("id-number").innerHTML="no. 00" + pokemon_ID;
<div id="id-number"></div>
What is wrong in the code?
Full code:
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM pokemons where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
Database::disconnect();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="pokedex">
<div id="left">
<div id="top-left">
<div id="top-leds">
<div id="top-red-led"></div>
<div id="top-yellow-led"></div>
<div id="top-green-led"></div>
</div>
</div>
<div id="led"></div>
<div id="left-triangle"></div>
<div id="screen-border">
</div>
<div id="screen">
<div class="name"><?php echo $data['name'];?></div>
</div>
<div id="cross">
<div id="center">
<div id="cross-center">
<div id="center-circle"></div>
</div>
<div id="up-btn">
<div id="upAr"></div>
</div>
<a id="right-btn" onclick="increasePokemon_ID()">
<div id="rightAr"></div>
</a>
<div id="left-btn">
<div id="leftAr"></div>
</div>
<div id="down-btn">
<div id="downAr"></div>
</div>
</div>
</div>
<div id="id-number"></div>
<div id="blue-btn"></div>
</div>
<div id="middle">
<div id="charniere-haute"></div>
<div id="charniere-basse"></div>
</div>
<div id="right">
<div id="info-screen"></div>
<div id="right-triangle"></div>
<div id="left-arrow-button">
<div id="left-arrow"></div>
</div>
<div id="right-arrow-button">
<div id="right-arrow"></div>
</div>
<div id="keyboard">
<div class="top-key"></div>
<div class="top-key"></div>
<div class="top-key"></div>
<div class="top-key"></div>
<div class="top-key"></div>
<div class="bottom-key"></div>
<div class="bottom-key"></div>
<div class="bottom-key"></div>
<div class="bottom-key"></div>
<div class="bottom-key">Help</div>
</div>
<div id="type-display1"><?php echo $data['type'];?></div>
<div id="type-display2"></div>
</div>
</div>
<script>
var pokemon_ID = 0;
function increasePokemon_ID() {
pokemon_ID++;
document.getElementById("id-number").innerHTML="no. 00" + pokemon_ID;
}
document.getElementById("right-btn").onclick = function() {
increasePokemon_ID();
}
</script>
</body>
</html>

The value is actually being incremented, but you're not showing the updated value to the div.
Try this:
var pokemon_ID = 0;
var el = document.getElementById("id-number");
function increasePokemon_ID() {
pokemon_ID++;
el.innerHTML = "no. 00" + pokemon_ID;
}
<a id="right-btn" onclick="increasePokemon_ID()">
<div id="id-number">0</div>

This is because you are not updating the HTML on click, but just updating the value of a variable. You can add the document.getElementById("id-number").innerHTML="no. 00" + pokemon_ID; to your onclick function or to the increasePokemon_ID function.

Related

drop down search bar on click with history?

I want to add a feature to my current search bar where if I click, I am able to see a drop down of all the previous inputs. And if I were to click on this previous input, it will run my code again. I am a current boot camp student and I just need guidance into how to make this work. If someone to just point me in the right direction, or explain some sample functions that would be really helpful. Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="./assets/style.css" />
<title>Weather Dashboard</title>
</head>
<body onload="load()">
<div class="container">
<div class="card">
<div class="row">
<div class="col-9 left">
<nav class="row top">
<div class="col" id="cityName">City Name</div>
<form class="form-outline">
<input
type="search"
id="userInput"
class="form-control"
placeholder="search for a city"
aria-label="Search"
/>
</form>
<div class="col" id="date">Date</div>
</nav>
<div class="row">
<div class="col-7 temp" id="temperature">15°</div>
<div class="col-5 time">
<p id="time">11:00</p>
<h2 id="today"><b>Saturday</b></h2>
<p id="conditions">Cloudy</p>
</div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row" id="condition1">Condition</div>
<div class="row data"><img id="conditionIcon1" /></div>
</div>
<div class="col">
<div class="row" id="condition2">Condition</div>
<div class="row data"><img id="conditionIcon2" /></div>
</div>
<div class="col">
<div class="row" id="condition3">Condition</div>
<div class="row data"><img id="conditionIcon3" /></div>
</div>
<div class="col">
<div class="row" id="condition4">Condition</div>
<div class="row data"><img id="conditionIcon4" /></div>
</div>
<div class="col">
<div class="row" id="condition5">Condition</div>
<div class="row data"><img id="conditionIcon5" /></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row" id="date1">Sun</div>
<div class="row data" id="date1Temp"><b>0°</b></div>
</div>
<div class="col">
<div class="row" id="date2">Mon</div>
<div class="row data" id="date2Temp"><b>0°</b></div>
</div>
<div class="col">
<div class="row" id="date3">Tue</div>
<div class="row data" id="date3Temp"><b>0°</b></div>
</div>
<div class="col">
<div class="row" id="date4">Wed</div>
<div class="row data" id="date4Temp"><b>0°</b></div>
</div>
<div class="col">
<div class="row" id="date5">Thu</div>
<div class="row data" id="date5Temp"><b>0°</b></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity1"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity2"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity3"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity4"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Humidity</div>
<div class="row data" id="humidity5"><b>0°</b></div>
</div>
<div class="col"><hr /></div>
</div>
<div class="row bottom">
<div class="col"><hr /></div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed1"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed2"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed3"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed4"><b>0°</b></div>
</div>
<div class="col">
<div class="row">Wind Speed</div>
<div class="row data" id="windSpeed5"><b>0°</b></div>
</div>
<div class="col"><hr /></div>
</div>
</div>
<div class="col-3 right">
<div class="row top" id="right-header">Today's Statistics</div>
<div class="timely">
<div class="row">Temp High:<b id="tempHigh">0°</b></div>
<div class="row">Temp Low:<b id="tempLow">0°</b></div>
<div class="row">Feels Like:<b id="feelslike">0°</b></div>
<div class="row">Wind Speed:<b id="windspeed">0°</b></div>
<div class="row">Humidity:<b id="humidity">0°</b></div>
<div class="row">Pressure:<b id="pressure">0°</b></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs#1/dayjs.min.js"></script>
<script>
dayjs().format();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="./assets/script.js"></script>
</body>
</html>
const date = document.querySelector("#date");
const time = document.querySelector("#time");
const dayOfWeek = document.querySelector("#today");
const input = document.querySelector("#userInput");
date.innerText = moment().format("MMMM Do YYYY");
time.innerText = moment().format("h:mm A");
dayOfWeek.innerText = moment().format("dddd");
// applies elements on page load with current position
function load() {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
let fiveDayURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(fiveDayURL)
.then((res) => {
return res.json();
})
.then((data) => {
fiveDayWeather(data);
console.log(data);
localStorage.setItem("response", JSON.stringify(data.city.name));
loadUrl();
});
});
}
function loadUrl() {
let cityName = JSON.parse(localStorage.getItem("response"));
let requestURL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(requestURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
displayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
}
// uses user input as parameter to getApi()
input.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault();
// let cityName = document.querySelectro("#userInput").value;
// let li = document.createElement("li")
// li.innerText = cityName;
// document.querySelector('ul');
// ul.appendChild(li);
getApi();
input.value = "";
}
});
// fetches api using the user input
function getApi() {
let cityName = document.querySelector("#userInput").value;
let requestURL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(requestURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
displayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
}
// uses api data from getApi() and replaces text in html
let displayWeather = function (weatherData) {
document.querySelector("#cityName").innerText = weatherData.name;
document.querySelector("#temperature").innerText =
Math.floor(weatherData.main.temp) + "\u00B0";
document.querySelector("#conditions").innerText =
weatherData.weather[0].description;
document.querySelector("#tempHigh").innerText =
weatherData.main.temp_max + "\u00B0 F";
document.querySelector("#tempLow").innerText =
weatherData.main.temp_min + "\u00B0 F";
document.querySelector("#feelslike").innerText =
weatherData.main.feels_like + "\u00B0 F";
document.querySelector("#windspeed").innerText =
weatherData.wind.speed + " MPH";
document.querySelector("#humidity").innerText =
weatherData.main.humidity + "%";
document.querySelector("#pressure").innerText =
weatherData.main.pressure + " hPa";
let fiveDayURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${weatherData.coord.lat}&lon=${weatherData.coord.lon}&appid=b169b31281ffa2a2b70b9e8ac22c3e88&units=imperial`;
fetch(fiveDayURL)
.then((res) => {
return res.json();
})
.then((data) => {
// console.log(data);
fiveDayWeather(data);
})
.catch(() => {
alert("Unable to connect to OpenWeather");
});
};
// obtains lon and lat from previous function then completes new fetch to display 5 day forecast
let fiveDayWeather = function (weatherValue) {
let todaysMonth = dayjs().$M;
for (let i = 1; i < 6; i++) {
document.querySelector("#date" + i).innerText = `${todaysMonth}/${
dayjs().$D + i
}`;
document.querySelector("#date" + i + "Temp").innerText =
weatherValue.list[i].main.temp + "\u00B0 F";
document.querySelector("#condition" + i).innerText =
weatherValue.list[i].weather[0].description;
document.querySelector("#conditionIcon" + i).src =
"http://openweathermap.org/img/wn/" +
weatherValue.list[i].weather[0].icon +
"#2x.png";
document.querySelector("#humidity" + i).innerText =
weatherValue.list[i].main.humidity + "%";
document.querySelector("#windSpeed" + i).innerText =
weatherValue.list[i].wind.speed + "MPH";
}
};
You can store and retrieve the search history as an array to the local storage this way:
// our array
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
// storing our array as a string
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
// retrieving our data and converting it back into an array
var retrievedData = localStorage.getItem("quentinTarantino");
var movies2 = JSON.parse(retrievedData);
//making sure it still is an array
alert(movies2.length);
You retrieve the array from local storage and add it to the dropdown of the search box. When you search another query string, push it to the retrieved array and store it to local storage again. Hope it helps!
Hello I saw the code and I could suggest you few points-
Create an array and store the e.target.value from your #userinput when the enter key is pressed. If you want you can store the data in local storage as well at the later stage.
Then through an event listener in the input box mention the values stored in the array in list form(Probably use simple ul, li format combination and then style it later).
You also need to be able to pick the value of the history inputs which user selects and for that one way is to use event listeners in all the items of the array.
Now just call the api or whatever you want to do with the e.target.value from one of the event listeners.

Add anchor tags dynamically to a div when page load in Javascript

I have 2 divs that all have the same css class, as follows:
/*div 1 */
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://test.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
/*div 2 */
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://example.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
As you can see, both main divs have oxilab-flip-box-col-5 class and each has an ahref tag, now I want all the div components to be linked when the page is loaded, as follows:
/*div 1 */
<a href="http://test.com" target="">
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
.
.
.
</div>
</a>
/*div 2 */
<a href="http://example.com" target="">
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
.
.
.
</div>
</a>
I was able to write this code with JavaScript, but unfortunately, the code I wrote does not work.
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);
Any idea how I can do this and link each div separately ?
Here You Go:
var first_div = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var parent1 = first_div.parentNode;
var a_tag1 = document.createElement('a');
parent1.replaceChild(a_tag1, first_div)
a_tag1.appendChild(first_div)
a_tag1.setAttribute('href',"http://example.com");
/////////
var second_div = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var parent2 = second_div.parentNode;
var a_tag2 = document.createElement('a');
parent2.replaceChild(a_tag2, second_div)
a_tag2.appendChild(second_div)
a_tag2.setAttribute('href',"http://example.com");
getElementsByClassName return an HTMLCollection of elements.
Change your code to:
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);
You should try to DRY (Don't Repeat Yourself). You can see that you do 2 times the same thing. What if you need to do it 100 times? Then your code will get messy quickly.
You'll see 2 solutions in my code: the ugly way (not DRY) and the cleaner way (DRY). There's a even cleaner way but let's start with this ;)
/*THE UGLY WAY*/
/*
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var first_link = document.createElement('a');
first_link.setAttribute('href',"http://test.com");
first_link.innerText = "some text1";
first_link.append(fisrtdiv);
document.body.append(first_link);
//we take again at index 0 because before this line we changed the position of the flip boxes
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var second_link = document.createElement('a');
second_link.setAttribute('href',"http://example.com");
second_link.innerText = "some text2";
second_link.append(seconddiv);
document.body.append(second_link);
*/
/*CLEANER WAY*/
var
list_of_flip_boxes = document.querySelectorAll(".oxilab-flip-box-col-5"),
list_of_links = [
{
text : "some text 1",
href : "http://test.com"
},
{
text : "some text 2",
href : "http://example.com"
},
];
list_of_flip_boxes.forEach(function(flip_box, index){
var
link_element = document.createElement("a"),
link_data = list_of_links[index];
link_element.setAttribute('href', link_data.href);
link_element.innerText = link_data.text;
link_element.append(flip_box);
document.body.append(link_element);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://test.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://example.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Unable to remove parent div of dynamically created cards

I want to remove a Parent div using js or jquery but I am unable to do so because it is multiple cards made dynamically. Here is my code:
<?php
for($ter as $term)
{
<div class="wrapper-newjoinee-custom">
<div class="breadcrumbs joinee-firstchild">
<h2 class="section-heading blue-bar">
<?php
echo $term->name;
?>
</h2>
</div>
<div class="row-joinee">
<?php echo $term->data; ?>
</div>
</div>
}
?>
main.js file:
jQuery(document).live(function($) {
if ( $('.row-joinee').text().length == 0 ) {
// length is 0
$('.row-joinee').closest(".wrapper-newjoinee-custom").remove();
}
});
please help me to make display none of wrapper-newjoinee-custom class if row-joinee class is empty
You could try something like this:
$(".row-joinee").filter(
function() { return $(this).text().trim() == ""})
.closest(".wrapper-newjoinee-custom").hide()
This will hide those .wrapper-newjoinee-custom that has en empty <div class="row-joinee">
Demo
$(".row-joinee").filter(function() { return $(this).text().trim() == ""}).closest(".wrapper-newjoinee-custom").hide()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper-newjoinee-custom">
<div class="breadcrumbs joinee-firstchild">
<h2 class="section-heading blue-bar">
name
</h2>
</div>
<div class="row-joinee">
data
</div>
</div>
<div class="wrapper-newjoinee-custom">
<div class="breadcrumbs joinee-firstchild">
<h2 class="section-heading blue-bar">
name im empty
</h2>
</div>
<div class="row-joinee"></div>
</div>
<div class="wrapper-newjoinee-custom">
<div class="breadcrumbs joinee-firstchild">
<h2 class="section-heading blue-bar">
name
</h2>
</div>
<div class="row-joinee">
data
</div>
</div>

How to hide a div if another has no content

I have some code where I need to hide a div if another is empty.
Basically, if .plant_profile_link has no content, hide .plant_profile_display
My attempt
$(document).ready(function() {
if (!$.trim($(".plant_profile_link").html()) == true)
$(".plant_profile_display").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et_pb_text_inner">
<div class="plant_profile_display">Bobo</div>
</div>
</div>
<!-- .et_pb_text -->
<div class="et_pb_module et_pb_text et_pb_text_7_tb_body et_pb_text_align_left et_pb_bg_layout_light">
<div class="et_pb_text_inner">
<div class="plant_profile_link"></div>
</div>
<div class="et_pb_text_inner">
<div class="plant_profile_link"></div>
</div>
Your code works if we add jQuery
I would user toggle
$(function() {
$(".plant_profile_display").toggle($(".plant_profile_link").text().trim() !== "");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et_pb_text_inner">
<div class="plant_profile_display">Bobo</div>
</div>
</div>
<!-- .et_pb_text -->
<div class="et_pb_module et_pb_text et_pb_text_7_tb_body et_pb_text_align_left et_pb_bg_layout_light">
<div class="et_pb_text_inner">
<div class="plant_profile_link"></div>
</div>
<div class="et_pb_text_inner">
<div class="plant_profile_link"></div>
</div>
Maybe something like this suits you
$(document).ready(function() {
var $plantLinks = $('.plant_profile_link')
var $plantDisplay = $('.plant_profile_display')
if($plantLinks.children().length > 0 || $plantLinks.text().length > 0) {
$plantDisplay.show();
} else {
$plantDisplay.hide();
}
});

Error in d3.js using jQuery and dc.js

I'm new in programming, and I'm trying to implement a search button that can enable me to filter datas .
I have on my serv a JSON data at the url /tweets_complet . Then I want to get another JSON which depends on the input from the search button . Once I have the two JSON, I wrote some code, which I think is not important .
Here is the js code :
function main(){
$.getJSON("/tweets_complet", insererDonneesJson);}
function insererDonneesJson(data){
$('button').on('click', get_data);
function get_data() {
var cashtagg=$('#cash').val();
$.getJSON("/"+cashtagg, filter);
function filter(data2) {
//Tweets datas
var tweets = data;
var dateFormat = d3.time.format("%Y-%m-%d %H:%M:%S");
tweets.forEach(function(d) {
d["cleandate"] = dateFormat.parse(d["cleandate"]);
d["cleandate"].setSeconds(0);
});
//Create a Crossfilter instance
var ndx = crossfilter(tweets);
//Define Dimensions
var cleandateDim = ndx.dimension(function(d) { return d["cleandate"]; });
var sentimentDim=ndx.dimension(function(d) { return d["sentiment"]; });
var bnscoreDim=ndx.dimension(function(d) { return d["bnscore"]; });
var tickerDim=ndx.dimension(function(d) { return d["collection_name"];});
var newTickerDim = tickerDim.filter(cashtagg);
//Calculate metrics
var numTweetsByTicker=newTickerDim.group()
var numTweetsByDate = cleandateDim.group();
var numTweetsByBnscore = bnscoreDim.group();
var totalScoreByDate = cleandateDim.group().reduceSum(function(d) {
return d["sentiment"]*10/(numTweetsByDate.size());})
var all = ndx.groupAll();
var numTweetsBySentiment = sentimentDim.group();
//Define values (to be used in charts)
var minDate = cleandateDim.bottom(1)[0]["cleandate"];
var maxDate = cleandateDim.top(1)[0]["cleandate"];
//Datas cashtag
var datas = data2;
var dateFormatO = d3.time.format("%Y-%m-%d");
datas.forEach(function(d) {
d["Date"] = dateFormatO.parse(d["Date"]);
});
// Create a Crossfilter instance
var ndxO = crossfilter(datas);
// Define Dimensions
var dateDimO = ndxO.dimension(function(d) { return d["Date"]; });
var volumeDimO=ndxO.dimension(function(d) { return d["Volume"]; });
var scoreDimO=ndxO.dimension(function(d) { return d["Low"]; });
// Calculate metrics
var groupeVolumeO = dateDimO.group().reduceSum(function(d) { return d["Volume"]/10000000;});
var groupeScoreO = dateDimO.group().reduceSum(function(d) { return d["Low"];});
var allO = ndxO.groupAll();
// Define values (to be used in charts)
var minDateO = dateDimO.bottom(1)[0]["Date"];
var maxDateO = dateDimO.top(1)[0]["Date"];
var minVolumeO = (volumeDimO.bottom(1)[0]["Volume"])/10000000;
var maxVolumeO = (volumeDimO.top(1)[0]["Volume"])/10000000;
var minScoreO = scoreDimO.bottom(1)[0]["Low"];
var maxScoreO = scoreDimO.top(1)[0]["Low"];
//Charts
var timeChart = dc.barChart("#time-chart");
var pieChart= dc.pieChart("#pie-chart")
var numberTweetsND = dc.numberDisplay("#number-tweets-nd");
var hitslineChart = dc.lineChart("#chart-line-hitsperday");
var shareChart = dc.lineChart("#share-chart");
var volumeChart = dc.lineChart("#volume-chart");
numberTweetsND
.formatNumber(d3.format("d"))
.valueAccessor(function(d){return d; })
.group(all);
timeChart
.width(800)
.height(160)
.margins({top: 10, right: 50, bottom: 30, left: 50})
.dimension(cleandateDim)
.group(numTweetsByDate)
.transitionDuration(500)
.x(d3.time.scale().domain([minDate, maxDate]))
.elasticY(true)
.xAxisLabel("Day")
.yAxis().ticks(8);
pieChart.width(350)
.height(330)
.dimension(sentimentDim)
.group(numTweetsBySentiment)
.colors(['red','black','green']);
hitslineChart
.width(600).height(330)
.dimension(cleandateDim)
.group(totalScoreByDate)
.x(d3.time.scale().domain([minDate,maxDate]));
volumeChart
.width(800).height(330)
.dimension(dateDimO)
.group(groupeVolumeO)
.x(d3.time.scale().domain([minDateO,maxDateO]));
// .y(d3.scale.linear().domain([minVolumeO,maxVolumeO]));
shareChart
.width(800).height(330)
.dimension(dateDimO)
.group(groupeScoreO)
.x(d3.time.scale().domain([minDateO,maxDateO]));
// .y(d3.scale.linear().domain([minScoreO,maxScoreO]));
dc.renderAll();
}}};
$(document).on('ready', main);
And the HTML code :
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
<link rel="stylesheet" href="./static/lib/css//bootstrap.min.css">
<link rel="stylesheet" href="./static/lib/css/keen-dashboards.css">
<link rel="stylesheet" href="./static/lib/css/dc.css">
<link rel="stylesheet" href="./static/css/custom.css">
</head>
<body class="application">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="./">InTwittiv</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Description</li>
<li>Analyse</li>
</ul>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<!-- <a href="#" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-search"></span>
<div class="col-sm-10">
<input type="text" class="form-control" id="cashtag" placeholder="Cashtag">
</div>
</a> -->
<div class="col-sm-3 col-md-3 pull-right">
<div class="form-group">
<input id="cash" type="text" placeholder="Change Cashtag here" >
<button class="btn btn-sm btn-success">Chercher</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-6">
<div class="row">
<div class="col-sm-12">
<div class="chart-wrapper">
<div class="chart-title">
Tweet Volume
</div>
<div class="chart-stage">
<div id="time-chart"></div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="chart-wrapper">
<div class="chart-title">
Sentiment repartition
</div>
<div class="chart-stage">
<div id="pie-chart"></div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="chart-wrapper">
<div class="chart-title">
Sentiment repartition
</div>
<div class="chart-stage">
<div id="chart-line-hitsperday"></div>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="chart-wrapper">
<div class="chart-title">
Total nb of tweets
</div>
<div class="chart-stage">
<div id="number-tweets-nd"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-12">
<div class="chart-wrapper">
<div class="chart-title">
Volume (*10^6)
</div>
<div class="chart-stage">
<div id="volume-chart"></div>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="chart-wrapper">
<div class="chart-title">
Share Price
</div>
<div class="chart-stage">
<div id="share-chart"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<p class="small text-muted">Built by Keyrus Capital Markets</p>
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="./static/lib/js/bootstrap.min.js"></script>
<script src="./static/lib/js/crossfilter.js"></script>
<script src="./static/lib/js/d3.js"></script>
<script src="./static/lib/js/dc.js"></script>
<script src="./static/lib/js/queue.js"></script>
<script src="./static/lib/js/d3.layout.cloud.js"></script>
<script src="./static/lib/js/keen.min.js"></script>
<script src='./static/js/graph2.js' type='text/javascript'></script>
</body>
</html>
When I run the serv, I can enter a value in the input (FB for example) and it works . However, from here, I can't change the "cash" value into something else like AAPL since I get the error
Uncaught TypeError: undefined is not a function
d3.js:2716
This line is :
var n = d3_time_numberRe.exec(string.slice(i, i + 4));
I have no clue about the reason of the issue since I'm not familiar with $ and buttons...
Any help would be appreciated :)

Categories

Resources