fail to modify content of template - javascript

<template id="entry-temp">
<li id="movie-list">
<span id="movie-info"> <span id = "li-movie-title"></span> (<span id = "li-movie-year"></span>) - <span id = "li-movie-rating"></span></span>
<button type="submit" id="movie-edit" name="movie-edit">edit</button>
<button type="submit" id="movie-delete" name="movie-delete">delete</button>
</li>
</template>
function appendMovie(title, year, rating) {
let template = document.querySelector("#entry-temp");
let tempNode = document.importNode(template.content, true);
tempNode.querySelector("#li-movie-title").innerHTMl = title;
tempNode.querySelector("#li-movie-year").innerHTMl = year;
tempNode.querySelector("#li-movie-rating").innerHTMl = rating;
let moviePanel = document.getElementById("movie-panel");
alert(tempNode.innerHTMl);
moviePanel.appendChild(tempNode);
}
The alert gives me undefined, and tempNode is a document fragment.
Also, is there a better way to print out the tag in JavaScript for debugging?
For example, How can I check if I really write title, year, and rating?

Related

How to get const from forEach method in javascript?

I have django application with quiz model:
class Quiz(models.Model):
name = models.CharField(max_length=50)
topic = models.CharField(choices=TOPICS, max_length=50)
number_of_questions = models.IntegerField(validators=[MinValueValidator(1)])
time = models.IntegerField(help_text="duration of quiz in minutes", default=5)
pass_score = models.IntegerField(help_text="score required to pass in %", default=90, validators = [MaxValueValidator(100), MinValueValidator(0)])
difficulty = models.CharField(choices=DIFFICULTY_CHOICES, max_length=10)
I get it in view:
def quiz_view(request, pk):
quiz = models.Quiz.objects.get(pk=pk)
return render(request, 'quizes/quiz.html', {'obj':quiz})
Then I get data of obj in html:
{% for obj in object_list %}
<button class="modal-button" data-pk="{{ obj.pk }}" data-name="{{ obj.name }}" data-topic="{{ obj.topic }}" data-questions="{{ obj.number_of_questions }}" data-difficulty="{{ obj.difficulty }}" data-time="{{ obj.time }}" data-pass="{{ obj.pass_score }}">
{{ obj.name }}
</button>
{% endfor %}
<div id="modal"></div>
Then I get data from button in javascript forEach method:
let modal = document.getElementById('modal')
const modalBtns = [...document.getElementsByClassName('modal-button')]
modalBtns.forEach(modalBtn => modalBtn.addEventListener('click', ()=>{
const pk = modalBtn.getAttribute('data-pk')
const name = modalBtn.getAttribute('data-name')
const topic = modalBtn.getAttribute('data-topic')
const numQuestions = modalBtn.getAttribute('data-questions')
const difficulty = modalBtn.getAttribute('data-difficulty')
const passScore = modalBtn.getAttribute('data-pass')
const time = modalBtn.getAttribute('data-time')
if(modal.classList.contains('close-modal')){
modal.classList.remove('close-modal')
}
modal.classList.add('open-modal')
modal.innerHTML = `
<p class="text">Are you sure you want to open</p><p class="name_of_quiz"><b>${name}?</b></p>
<ul class="description">
<li>Topic: ${topic}</li>
<li>Questions: ${numQuestions}</li>
<li>Difficulty: ${difficulty}</li>
<li>Score to pass: ${passScore}%</li>
<li>Time to solve: ${time} min</li>
</ul>
<div class="buttons-container">
<button class="close-button" onclick="close_modal()">Close</button>
<button class="proceed-button" id='start_button' onclick="startQuiz()">Yes</button>
</div>
`
}))
So when user clicks on button it sets open-modal:
.open-modal{
visibility: visible !important;
}
And we can see it. Then when I click 'proceed-button', I should get pk by running startQuiz():
function startQuiz(){
console.log(pk)
}
But I get an error:
`'pk' is not defined'.
Can I somehow get pk from forEach method?
i found your problem. You can't use a const. Constants have a block scope. Use parameters instead. A snippet of your javascript could be:
let modal = document.getElementById('modal')
const modalBtns = [...document.getElementsByClassName('modal-button')]
modalBtns.forEach(modalBtn => modalBtn.addEventListener('click', ()=>{
const pk = modalBtn.getAttribute('data-pk')
const name = modalBtn.getAttribute('data-name')
const topic = modalBtn.getAttribute('data-topic')
const numQuestions = modalBtn.getAttribute('data-questions')
const difficulty = modalBtn.getAttribute('data-difficulty')
const passScore = modalBtn.getAttribute('data-pass')
const time = modalBtn.getAttribute('data-time')
if(modal.classList.contains('close-modal')){
modal.classList.remove('close-modal')
}
modal.classList.add('open-modal')
modal.innerHTML = `
<p class="text">Are you sure you want to open</p><p class="name_of_quiz"><b>${name}?</b></p>
<ul class="description">
<li>Topic: ${topic}</li>
<li>Questions: ${numQuestions}</li>
<li>Difficulty: ${difficulty}</li>
<li>Score to pass: ${passScore}%</li>
<li>Time to solve: ${time} min</li>
</ul>
<div class="buttons-container">
<button class="close-button" onclick="close_modal()">Close</button>
<button class="proceed-button" id='start_button' onclick="startQuiz(${pk})">Yes</button>
</div>
`
}))
function startQuiz(pk){
console.log(pk)
}
With some value types it can happen that it doesn't work properly. If it doesn't work, write a comment with the type of pk.

click event listener method is not working on a specific div

I am trying to add an event listener to my "degree section div" but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the "degree-section" div but to no avail.
Any kind of help is welcome and appreciated
Code:
let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];
//let wind = document.querySelector('.wind');
async function getUrl(city) {
try {
let theUrl = url + city + '&appid=' + apiKey;
let response = await fetch(theUrl, {
mode: 'cors'
})
let data = await response.json();
//Get data from api and change html content based on the recieved data
let temp_data = data.main.temp
temp.textContent = temp_data;
let feels_like_data = data.main.feels_like;
feels_like.textContent = feels_like_data + "K";
let humidity_data = data.main.humidity;
humidity.textContent = humidity_data;
let {
icon
} = data.weather[0];
locationIcon.innerHTML = `<img src="icons/${icon}.png">`;
//change K to C
degree_section.addEventListener('click', () => {
//logging a message just to check if it is working
console.log("c")
})
} catch (err) {
let error = document.createElement('span')
error.className = "error";
error.textContent = "Location does not exist"
let top_center_div = document.querySelector('.top-center')
top_center_div.appendChild(error)
city_name.textContent = "No city found"
}
}
searchbtn.addEventListener('click', (e) => {
let cityName = city.value;
city_name.textContent = cityName
console.log(cityName)
getUrl(cityName)
})
<body>
<div class="loc-container">
<div class="location">
<h1 class="city-name">City</h1>
<div class="weather-icon"><img src="icons/unknown.png" /></div>
</div>
</div>
<div class="weather-info">
<div class="degree-section">
<h2 class="temp">0.0</h2>
<span>K</span>
</div>
<div class="info-section">
<div class="info-flex">
<h3 class="feels-like">0K</h3>
<h4>Feels Like</h4>
</div>
<div class="info-flex">
<h3 class="humidity">0</h3>
<h4>Humidity</h4>
</div>
<div class="info-flex">
<h3 class="wind">0</h3>
<h4>Wind</h4>
</div>
</div>
</div>
<div class="top-center">
<div class="form">
<input type="text" name="city" id="city" required>
<label for="city" class="label-name"><span class="search-name">Search City...</span></label>
</div>
<!-- <i class="fas fa-search search-btn"></i> -->
<i class="material-icons search-btn" style="font-size: 35px;">search</i>
</div>
<script src="weather.js"></script>
</body>
This is what "data" looks like
{"coord":{"lon":72.8479,"lat":19.0144},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":303.14,"feels_like":303.45,"temp_min":301.09,"temp_max":303.14,"pressure":1014,"humidity":45},"visibility":2500,"wind":{"speed":3.09,"deg":120},"clouds":{"all":20},"dt":1638773692,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1638754125,"sunset":1638793848},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}
Thank you in advance!
I believe the problem is with
let degree_section_span = degree_section.getElementsByTagName('span')[0];
since it selects the wrong element. Try changing it to
let degree_section_span = weather_sec.querySelector('.check');
and see if it works. You can also change the variable name to something more appropriate, while you're at it.
EDIT:
I think this is what you're trying to do. For the sake of siplicity , I removed everything not related to temp:
let target = weather_sec.querySelector("div.check"),
temp_data = data.main.temp;
temp.textContent = temp_data;
target.addEventListener('click', () => {
cel = parseInt(temp_data) - 273.15;
temp.textContent = cel.toFixed(2);
temp.nextElementSibling.textContent = "C";
});
So after 48hrs of debugging I finally figured out what is wrong. If you see in my HTML I have a div.top-center at the bottom. And due to some dimension issues in my css file the height of div.top-center spanned the entire page so essentially all of my divs were being wrapped inside div.top-center so even if I assigned a click event to my div.degree-section the target was always div.top-center and that is why the click event was not showing the proper output.

adding a date to the items in the list and displaying them on a webpage

I am completely lost on a task where I have to add a date to the items when they are created, store them in a list and then present on my webpage.
my javascript code
var counter=4;
var completelist = document.getElementById("thelist");
var currentTime = new Date();
todo=[todo1,todo2,todo3];
todoButton.onclick=function addelement() {
var userTodoInput = document.getElementById("todoInput");
if(userTodoInput.value!=="" ){
let node = document.createElement("LI");
node.innerHTML = userTodoInput.value;
completelist.appendChild(node);
todo.push(userTodoInput);
document.getElementById("mydiv").innerHTML += "<div class='todo' ><p id='t-list'> You have added this to the list of actions: " + userTodoInput.value + "</p></br></div>";
} else {
alert("Enter something in textarea")
}
counter++;
}
My dom
<div class="todo-container" >
<h1 class="about-heading">The todo list </h1>
<p id="todo-paragraph">On this page you are able to add new items to your to-do list </p>
<div class="todo-items">
<ul id="thelist">
<li class="todo"id="todo1">Item 1</li>
<li class="todo" id="todo2">Item 2</li>
<li class="todo" id="todo3"> Item 3</li>
</ul>
<input id="todoInput" type="text" name="todoInput" placehoder="Type your to-do here">
<button id="todo-button" >Add Item </button>
<div id="mydiv">
</div>
</div>
what would you suggest on this?
The problem is, your todoButton is not defined anywhere in your code.
If you add var todoButton = document.getElementById("todo-button");, your script should be working.
EDIT:
If you want to append date to user input, check edited code below. I stored userTodoInput and currentTime to single variable, named newItem and then place the variable on places you need it. I hope this help.
var counter = 4;
var completelist = document.getElementById("thelist");
var currentTime = new Date();
todo = [todo1, todo2, todo3];
todoButton.onclick = function addelement() {
var userTodoInput = document.getElementById("todoInput");
if (userTodoInput.value !== "") {
let node = document.createElement("LI");
let newItem = `${userTodoInput.value} ${currentTime}`;
node.innerHTML = newItem;
completelist.appendChild(node);
todo.push(newItem);
document.getElementById("mydiv").innerHTML += "<div class='todo' ><p id='t-list'> You have added this to the list of actions: " + newItem + "</p></br></div>";
} else {
alert("Enter something in textarea")
}
counter++;
Take a look to the following commented code. Obviously it is a basic implementation, but I think that main concepts are clear:
// GET ELEMENTS.
const list = document.getElementById('list');
const input = document.getElementById('input');
const button = document.getElementById('button');
const onClickHandler = () => {
// CHECK FOR TO-DO NAME.
if (input.value) {
// USE ELEMENT CHILDREN COUNT AS INDEX.
const index = list.children.length;
// CREATE li ELEMENT PROGRAMMATICALLY.
const li = document.createElement('LI');
// INSTANTIATE A NEW DATE OBJECT.
const date = new Date();
// ADD ATTRIBUTES.
li.id = `todo${index}`;
li.class = 'todo';
li.innerText = `${input.value} - ${date.toString()}`;
// ADD ELEMENT TO DOM.
list.appendChild(li);
} else {
alert('Please type your to-do.')
}
};
// ADD EVENT LISTENER.
button.addEventListener('click', onClickHandler);
<div>
<h1>The todo list</h1>
<p>On this page you are able to add new items to your to-do list</p>
<div>
<ul id="list"></ul>
</div>
<input id="input" type="text" name="todo" placeholder="Type your to-do here">
<button id="button" type="button">Add Item</button>
</div>

Error with JavaScript Object

The code only processes the last string of the object and then proceeds based off of that one and doesn't display a child's name even if their birthday does match today's date when that child's string of data is not the last one entered into the object. I need some advice or help in how to make the javascript find each person whose birthday matches the date and display them instead of just looking at the last child's data
var studentProfile = [];
var index=0;
function saveProfile()
{
studentProfile[index] = {
firstName: document.getElementById("txtFirstName").value,
surname: document.getElementById("txtSurname").value,
birthday: document.getElementById("txtBirthday").value,
contactInfomation: document.getElementById("txtContactInfomation").value,
medicalInformation: document.getElementById("txtMedicalInformation").value,
}
index = index + 1;
localStorage.setItem("students", JSON.stringify(studentProfile));
}
function displayProfile()
{
for (var i = 0; i<studentProfile.length; i++) {
alert("The Student's Name is " + studentProfile[i].firstName + " " + studentProfile[i].surname + ".");
alert("The Student's Birthday is " + studentProfile[i].birthday + ".");
alert("The Student's Contact Information is: " + studentProfile[i].contactInfomation + ".");
alert("The Student's Medical Information is: " + studentProfile[i].medicalInformation) + ".";
}
}
function clearData()
{
document.getElementById("txtFirstName").value = "";
document.getElementById("txtSurname").value = "";
document.getElementById("txtBirthday").value = "";
document.getElementById("txtContactInfomation").value = "";
document.getElementById("txtMedicalInformation").value = "";
}
function birthday()
{
//state all the variables for the program and convert the JSON string from the register js back into an object
var studentProfile = new Object();
var studentBirthday;
var bdayMonth, bdayDay;
var birthDate = new Date();
var today = new Date();
var todayMonth;
var todayDay;
studentProfile = JSON.parse(localStorage.getItem("students"));
// this variable is for the birthday picture to disappear if there are no birthdays, its used later on in the code
var BirthdayBorder = document.getElementById("BirthdayBorder");
// this variable is for the text to change position if there are no birthdays, its used later on in the code
var txtbirthday = document.getElementById("txtContainer");
//I had an alert here to see if the javascript was accurately able to convert the string back into an object and after this is the actual programs code
for (var i = 0; i < studentProfile.length; i++)
{
//here is where the variables regarding the date were specified and extracted from the object that was converted
bdayMonth = studentProfile[i].birthday.substring(0,2);
bdayDay = studentProfile[i].birthday.substring(3,5);
todayMonth = today.getMonth()+1;
todayDay = today.getDate();
//this is where the comparison part of the code starts, basically the birthday entered by the user is compared with today's date
if ((bdayDay == todayDay) && (bdayMonth == todayMonth))
{
//if the dates are equal to one another then the student's firstname is determined and displayed as an output in the html
document.getElementById("birthdays").innerHTML = studentProfile[i].firstName;
BirthdayBorder.style.opacity = "100";
BirthdayBorder.style.marginTop = "0px";
txtbirthday.style.marginTop = "144px";
}
else
{
//the program has determined that there are no birthdays today and will display the text instead of a student's name
document.getElementById("birthdays").innerHTML = "No Birthdays Today! ;)";
//this is the styling part for the birthday border to be transparent and moved to a place where it isn't affecting the website's margins and the text is moved to look better than being in empty space
BirthdayBorder.style.opacity = "0";
BirthdayBorder.style.marginTop = "-1000px";
txtbirthday.style.marginTop = "-50px";
}
}
}
okay here is the requested other information
html:
The Plan
<div id="Titlecont">
<div id="Picture">
<img src="LogoPicture.png" width=60 height=60>
</div>
<div id="Title">
<h1>Little Hands Daycare</h1>
</div>
<div id="Motto">
<p> "It takes a village to raise a child" </p>
</div>
</div>
<div id="Button">
<a href="Computer SciencesWE.html">
<button type="button">
Home
</button>
</a>
<a href="Timer.html">
<button type="button">
Timer
</button>
</a>
<a href="About Us.html">
<button type="button">
About
</button>
</a>
<a href="Register.html">
<button type="button">
Register
</button>
</a>
<a href="Schedule.html">
<button type="button">
Events
</button>
</a>
<button type="button">
Contact
</button>
</div>
</div>
<!--This is where the daily schedule is coded-->
<br>
<div id="Schedule">
<img src="Calender.jpg" width=800 height=540>
<!--This is where the html displays the output of the js-->
<div id="txtContainer">
<p id="birthdays">
.
</p>
</div>
<div id="BirthdayBorder">
<img src="Birthday Border.jpg" width=800 height=600>
</div>
</div>
</body>
</html>
and the requested portion of the javascript has been added to the top of the old code
You have to stop looping when you find a match. Otherwise, you'll process the non-matching items after it, which overwrites the changes you made.
var birthday_found = false;
for (var i = 0; i < studentProfile.length; i++)
{
//here is where the variables regarding the date were specified and extracted from the object that was converted
bdayMonth = studentProfile[i].birthday.substring(0,2);
bdayDay = studentProfile[i].birthday.substring(3,5);
todayMonth = today.getMonth()+1;
todayDay = today.getDate();
//this is where the comparison part of the code starts, basically the birthday entered by the user is compared with today's date
if ((bdayDay == todayDay) && (bdayMonth == todayMonth))
{
//if the dates are equal to one another then the student's firstname is determined and displayed as an output in the html
document.getElementById("birthdays").innerHTML = studentProfile[i].firstName;
BirthdayBorder.style.opacity = "100";
BirthdayBorder.style.marginTop = "0px";
txtbirthday.style.marginTop = "144px";
birthday_found = true;
break;
}
}
if (!birthday_found)
{
//the program has determined that there are no birthdays today and will display the text instead of a student's name
document.getElementById("birthdays").innerHTML = "No Birthdays Today! ;)";
//this is the styling part for the birthday border to be transparent and moved to a place where it isn't affecting the website's margins and the text is moved to look better than being in empty space
BirthdayBorder.style.opacity = "0";
BirthdayBorder.style.marginTop = "-1000px";
txtbirthday.style.marginTop = "-50px";
}

How to get text from span->li->ul-> Element

Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});

Categories

Resources