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";
}
Related
I have a little problem, I repeat timepicker with *ngFor, but it's not working properly if I changed the time in one of them, it changes in all. And all have a different id. AN IDEA TO MAKE THE WORk PROPERLY?`
COMPONENT.HTML :
<div id="schedule" *ngFor="let i of Arr(num).fill(1)"
style="display: -webkit-inline-flex">
<timepicker id="timer" class="schedulItem" style="margin-top:-28px"
[(ngModel)]="mytime" [showMeridian]="isMeridian"
[minuteStep]="mstep" (ngModelChange)="changed()">
</timepicker>
<button (click)="addSchedule()"> + </button>
</div>
COMPONENT.TS:
Arr = Array; //Array type captured in a variable
num:number = 1;
mytime: Date;
addSchedule() {
this.num = this.num + 1 ;
var length = document.querySelectorAll('.schedul').length
var time = document.getElementById("timer");
time.id += length;
}
changed(): void {
var time = this.mytime.getHours() + ":" + this.mytime.getMinutes();
console.log(time);
}
I found the problem! the model was the problem [(ngModel)]="mytime". All time pickers to the same model and one gets changed it changes all of them.
There's a textarea in the webpage to enable user to add address. User may enter 'n' number of addresses by clicking on the Add Address button. When user clicks on the Display Address button, all the addresses entered should be displayed inside the "result" div tag as per following format:
Address 1
Address entered by user
Address 2
Address entered by user
.....
Here's the HTML code
<div id="body" align="left">
<h2>Address Details</h2>
Enter the Address : <textarea id="address"></textarea><br>
<button id="add" onclick="addAddress();">Add Address</button>
<button id="display" onclick="displayAddress();">Display Address</button>
</div>
<div id="result" align="right"></div>
Here's the JS function to accept the address and store it in an array:
var address = [];
function addAddress(){
var addr = document.getElementById("address");
if(addr.value.replace(/^\s+|\s+$/gm,'') !=="") {
address.push(addr.value);
addr.value = "";
}
}
And here's the function to display the address inside the result div in the specified format (which does not work)
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
}
result.innerHTML = addrno[i]+"<br>"+display[i]+"<br>";
}
Any help would be greatly appreciated.
Hm, if I understand your question correctly, you could try doing something like this:
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>";
}
}
All I changed was move result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>"; inside your for loop so it can access the variable i uppon each itteration and changed it so it added the string addrno[i]+"<br>"+display[i]+"<br>"; to the DOM by using += on result.innerHTML rather than = (so it doesn't override it, rather it appends to it)
I am a beginner in javascript, I am learning arrays. I am working on creating a html interface with javascript to use parallel arrays to obtain a users name and numeric value for each user (Score) I am stuck on understanding how I can save users input in each of the new arrays I created for each input. I have a button to save each name and score entry then I want to create a summary output that will check each score input and pass it through a loop to assign it a category such as A, B, C. I haven't gotten that far as I am confused on how to store each input in their array. The examples provided to me and the ones I found use predetermined values vs user input. This is what I have so far.
<h1>Grades</h1>
</header>
<br>
<p><b>Student Name:</b></p>
<input id="inp" type="text">
<br>
<br>
<p><b>Test Score:</b></p>
<input id="inps" type="text">
<br>
<br>
<br>
<button type="button" onclick="enter()">Enter</button>
<br>
<br>
<button type="button" onclick="summ()">Summary</button>
<br>
<p id="iop"></p>
<br>
<script>
var studentArr = new Array();
var scoreArr = new Array();
function enter() {
var studentName = document.getElementById("inp").value;
studentArr.push(inp);
var stuval = "";
for(i=0; i < studentArr.length; i++)
{
stuval = stuval + studentArr[i] + "<br/>";
}
document.getElementById("iop").innerHTML = stuval;
var studentScore = document.getElementById("inps").value;
scoreArr.push(inps);
var scoreval = "";
for(i=0; i < scoreArr.length; i++)
{
scoreval = scoreval + scoreArr[i] + "<br/>";
}
}
</script>
I belive more easier way exists:
var students = new Array();
function enter() {
students.push({
name: document.getElementById("inp").value,
score: document.getElementById("inps").value
});
show();
}
function show() {
document.getElementById("iop").innerHTML = "";
students.forEach(x => {
document.getElementById("iop").innerHTML += x.name + "<br/>";
});
}
You aren't using the right variable when pushing to your array here
studentArr.push(inp);
and here
scoreArr.push(inps);
Those variables do not exist in your code. You've defined 'studentName' and 'studentScore' so use them and you should have some data in your arrays.
In my Chrome extension, I'm trying to get info from a page (the value of "data-timestamp": 1490893300813) via a content script, but the result shows 'null'.
//content script:
var tsx = document.getElementsByClassName("date");
var i;
const ts = new Array;
for (i = 0; i < tsx.length; i++) {
var ts[i] = tsx[i].getAttribute("data-timestamp");
console.log("Timestamp" + i + ": " + ts[i]);
}
<!--source code from page:-->
<div class="thread">
<span data-timestamp="1490893300813" class="date">
<span class="absolute">Do, 30.03.2017, 19:01</span>
<span class="relative"></span>
</span>
</div>
I also noticed that the data-timestamp attribute is visible when I show source-code of the page (Ctrl+U) but it isn't visible in DevTools...
You can use document.querySelector('.date') to select the element that has the date class. From there, you can get the element.dataset.timestamp to get the timestamp.
Your code could look something like:
//Get the timestamp as a number ( + is used to convert from a string to a number).
var timestamp = +document.querySelector('.date').dataset.timestamp;
console.log('Timestamp:', timestamp);
//Convert to a Date and display in ISO format for the UTC timezone.
var date = new Date(timestamp);
console.log(date.toISOString());
<div class="thread">
<span data-timestamp="1490893300813" class="date">
<span class="absolute">Do, 30.03.2017, 19:01</span>
<span class="relative"></span>
</span>
</div>
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.