storing array of objects ang then check previous and next item - javascript

I should be able to add input for user A and user B and when I click previous it will display the previous one and when I click next it will display the next inputs back and forth. Thanks for any help.
It will ask input for user A after that we click next and will ask for input for user b after that when I click back it should display input of the previous user and if I click next if will display the next user.
but when I keep navigating next and prev it no longer display the data. waht is the issue with this guys ?
//event.js
const showModal = document.querySelector("#showModal");
const modal = document.querySelector(".modal");
const nextBtn = document.querySelector("#next-btn");
const prevBtn = document.querySelector("#prev-btn");
let userText = document.querySelector(".user-text");
showModal.addEventListener("click", e => {
modal.setAttribute("style", "display:block");
});
nextBtn.addEventListener("click", e => {
userText.textContent = "User B";
prevBtn.setAttribute("style", "display:inline-block");
});
prevBtn.addEventListener("click", e => {
userText.textContent = "User A";
prevBtn.setAttribute("style", "display:none");
});
//class.js
const mainForm = document.querySelector("#mainForm");
const fnameValue = document.querySelector("#fname");
const lnameValue = document.querySelector("#lname");
const idValue = document.querySelector("#idValue");
class User {
constructor() {
this.userArrHolder = [];
}
addUser(id, fname, lname) {
const newAddedUser = {
id: id,
fname: fname,
lname: lname,
};
if (this.userArrHolder.length > 0) {
// displaying first user in ui
this.userArrHolder.forEach(item => {
idValue.value = item.id;
fnameValue.value = item.fname;
lnameValue.value = item.lname;
console.log("display A");
});
// adding the second user
this.userArrHolder.push(newAddedUser);
} else {
// add new user
this.userArrHolder.push(newAddedUser);
fnameValue.value = "";
lnameValue.value = "";
}
}
// looping thru array
displayUser(id) {
idValue.value = id;
this.userArrHolder.forEach((item, index) => {
idValue.value = item.id;
fnameValue.value = item.fname;
lnameValue.value = item.lname;
});
}
}
const newUser = new User();
mainForm.addEventListener("submit", e => {
e.preventDefault();
// validating if adding a user or display
if (!idValue.value) {
let id = Math.floor(Math.random() * 10000);
newUser.addUser(id, fnameValue.value, lnameValue.value);
console.log("add", newUser.userArrHolder);
} else {
newUser.displayUser(idValue.value);
console.log("display", newUser.userArrHolder);
}
});
<!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="index.css" />
<title>Document</title>
</head>
<body>
<div class="show-modal">
<button id="showModal">Show Modal</button>
</div>
<div class="modal">
<div class="modal-wrapper">
<p class="user-text">User A</p>
<form action="" id="mainForm">
<label for="fname">First Name:</label><br />
<input type="text" name="fname" id="fname" /><br />
<label for="lname">Last Name:</label><br />
<input type="text" name="lname" id="lname" />
<div class="btn-container">
<button
type="submit"
id="prev-btn"
class="pr"
style="display: none"
>
Prev
</button>
<button type="submit" id="next-btn">Next</button>
</div>
<input type="text" name="idValue" id="idValue" />
</form>
</div>
</div>
</body>
</html>

Consider the following Example (using jQuery UI for Dialog)
$(function() {
var Users = [];
var pos = 0;
function showPrev() {
pos--;
showUser(Users[pos]);
if (pos == 0) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(0)").addClass("hidden");
}
if ($("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").hasClass("add-user")) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Next").removeClass("add-user ui-priority-primary");
}
}
function showNext() {
if ($("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").hasClass("add-user")) {
addUser($("#fname").val(), $("#lname").val());
showUser(Users[Users.length - 1]);
pos = Users.length - 1;
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Next").removeClass("add-user ui-priority-primary");
} else {
pos++;
if (pos == Users.length) {
showUser({
fname: "",
lname: "",
id: ""
});
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(1)").html("Add").addClass("add-user ui-priority-primary");
} else {
showUser(Users[pos]);
}
}
if (pos != 0) {
$("#show-users ~ div.ui-dialog-buttonpane div.ui-dialog-buttonset button:eq(0)").removeClass("hidden");
}
}
function newUser(fname, lname) {
return {
id: Math.floor(Math.random() * 10000),
fname: fname,
lname: lname
};
}
function addUser(fname, lname) {
Users.push(newUser(fname, lname));
}
function showUser(data, $target) {
$target = ($target != undefined ? $target : $("#show-users"));
$("#fname", $target).val(data.fname);
$("#lname", $target).val(data.lname);
$("#idValue", $target).val(data.id);
}
function makeTable(arr, $target) {
$target = ($target != undefined ? $target : $("body"));
var tbl = $("<table>", {
class: "ui-widget ui-corner-all"
}).css({
width: "100%",
borderCollapse: "collapse",
});
if ($target != false) {
tbl.appendTo($target);
}
if (arr.length == 0) {
return tbl;
}
var head = $("<thead>", {
class: "ui-widget-header"
}).appendTo(tbl);
var body = $("<tbody>", {
class: "ui-widget-content"
}).appendTo(tbl);
$("<tr>").appendTo(head);
$("<th>").html("ID").appendTo($("tr", head));
$("<th>").html("First Name").appendTo($("tr", head));
$("<th>").html("Last Name").appendTo($("tr", head));
$.each(arr, function(i, row) {
$("<tr>").appendTo(body);
$.each(row, function(k, v) {
$("<td>", {
class: "ui-widget-content"
}).html(v).appendTo($("tr:last", body));
});
});
$("tr", body).eq(pos).addClass("ui-priority-primary");
return tbl;
}
addUser("John", "Smith");
addUser("Jane", "Smith");
showUser(Users[pos]);
$("#show-users").dialog({
autoOpen: false,
modal: true,
buttons: [{
text: "Prev",
class: (pos != 0 ? "" : "hidden"),
click: showPrev
},
{
text: "Next",
click: showNext
},
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
$("#showModal").click(function() {
$("#show-users").dialog("open");
});
$("#showAll").click(function() {
var dlg = $("<div>", {
title: "All Users"
}).html(makeTable(Users, false));
dlg.dialog({
modal: true,
autoOpen: true,
close: function() {
$(this).dialog("destroy");
dlg.remove();
}
});
});
});
#mainForm label,
#mainform input {
display: block;
margin-bottom: 3px;
}
.ui-dialog .ui-dialog-buttonset button.hidden {
display: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="show-modal">
<button id="showModal">Show Modal</button>
</div>
<div class="show-all">
<button id="showAll">Show All Users</button>
</div>
<div class="modal" title="Show Users" id="show-users">
<form action="" id="mainForm">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" />
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" />
<input type="hidden" name="idValue" id="idValue" />
</form>
</div>
If you choose to not use the jQuery UI Dialog window, the other functions and basic ideas still apply.
You will have an Array of Users and an Pointer or Index counter, this will be set to 0 or the specific Index of the array. These should be available so you can read or modify them as needed. You will then have various functions to update the UI and modify data depending on the Users interactions.
Prev - Reduce the Pointer and show the Previous User data from the Array
Cannot drop below 0 index
Hide Prev button when Pointer is 0
Next - Increment the Pointer and show the Next User data from the Array
Cannot exceed last Index
Clear form for new User entry if on beyond the last Index
Show Prev button when Pointer is not 0

Related

Hiding the div and li elements when checkbox is checked/unchecked

Can anyone guide me in the correct direction please? I'm stuck with checked and not checked checkboxes. What I am trying to add:
Text in the text field & checkbox checked - hides the div element
Text in the text field & checkbox unchecked by entry - hides the first li element
Empty text field by entry & checkbox checked hides the second li element
What I have now:
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
cons.addEventListener("input", function() {
if (cons.checked && txt.value !== '') {
consError.style.display = "none"
but.disabled = false
} else {
consError.style.display = "block"
but.disabled = true
}
})
txt.addEventListener("input", function() {
if (txt.value !== '' && cons.checked === false) {
but.disabled
} else {
but.disabled = false
}
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox">
I agree
</label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script src="index.js"></script>
</body>
</html>
Before I had cons.addEventListener like this and it was hiding the second li element but didn't keep the button disabled
cons.addEventListener("input", function() {
if (cons.checked){
consError.style.display = "none"
} else {
consError.style.display = "block"
}
})
move the validator outside to single function like this
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A checkbox</title>
</head>
<body>
<label for="name">Name</label>
<input id="name" placeholder="Name">
<label>
<input id="consent" type="checkbox"> I agree </label>
<input id="send" type="button" value="Submit">
<p id="greeting"></p>
<div id="errors" style="color: red; display: none;">
<p>Error:</p>
<ul>
<li id="name-error">Please enter a name</li>
<li id="consent-error">Please give consent</li>
</ul>
</div>
<script>
let txt = document.getElementById("name")
let but = document.getElementById("send")
let out = document.getElementById("greeting")
let divv = document.getElementById("errors")
let nameError = document.getElementById("name-error")
let consError = document.getElementById("consent-error")
let cons = document.getElementById("consent")
but.disabled = true
divv.style.display = "block"
function validator() {
if (cons.checked && txt.value !== '') {
but.disabled = false
divv.style.display = "none"
} else {
but.disabled = true
divv.style.display = "block"
}
}
cons.addEventListener("change", function () {
if (cons.checked) {
consError.style.display = "none"
} else {
consError.style.display = "block"
}
validator();
})
txt.addEventListener("input", function () {
if (txt.value !== '') {
nameError.style.display = "none"
} else {
nameError.style.display = "block"
}
validator()
})
function fun() {
out.textContent = "Hey " + txt.value + "!"
}
but.addEventListener("click", fun)
</script>
</body>
</html>

Trying to add together multiple inputs in the same input field to get total value

tried cutting the code down as much as possible.
Issue: I'm trying to get the total price of new array objects that are being created from inputs by the user, i tried making a new function that grabs the input, but it changes to the new value in the input field whenever a new item is added. Price also wont change when the user deletes an object from the array.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
//Functions for user input for item name and price
function additemmore () {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if(document.getElementById("item-name-more").value.length == 0)
{
alert("Need a name")
return false;
}
if(document.getElementById("item-price-more").value.length == 0)
{
alert("Need a price")
return false;
}
if(document.getElementById("item-price-more").value === 0)
{
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore(){
itemListmore.innerHTML ="";
for(let i = 0; i < itemArrayMore.length; i++){
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
var total = +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
</head>
<body>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input
type="text"
id="item-name-more"
placeholder="Item name"
/>
<!--for some reason you can add the letter e in the input for price-->
<input
type="number"
id="item-price-more"
placeholder="Write name of item!"
/>
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Make total a global variable. Then you can add to it when you add a new item, and subtract from it when you delete an item.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
var total = 0;
//Functions for user input for item name and price
function additemmore() {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if (document.getElementById("item-name-more").value.length == 0) {
alert("Need a name")
return false;
}
if (document.getElementById("item-price-more").value.length == 0) {
alert("Need a price")
return false;
}
if (document.getElementById("item-price-more").value === 0) {
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore() {
itemListmore.innerHTML = "";
for (let i = 0; i < itemArrayMore.length; i++) {
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
total -= +itemArrayMore[i].price.replace('kr', '');
document.getElementById("total-price").innerHTML = total;
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
total += +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
</head>
<body>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input type="text" id="item-name-more" placeholder="Item name" />
<!--for some reason you can add the letter e in the input for price-->
<input type="number" id="item-price-more" placeholder="Write name of item!" />
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>

How to add recent search to searchbar in Vuejs?

enter() {
this.selection = this.matches[this.current];
this.open = false;
},
change() {
if (this.open == false) {
this.open = true;
this.current = 0;
}
if(this.search == "") {
this.isSearchText = false;
} else {
this.isSearchText = true;
}
},
inputChanged(event) {
if (event.code == "ArrowUp" || event.code == "ArrowDown")
return;
this.filteredUsers = [];
if (event.code == "Enter")
return;
var filtered = this.users.filter((user) => {
return user.text.match(this.search)
});
this.isOpen = true
this.filteredUsers.push(...filtered)
// console.log(this.filteredUsers)
},
onArrow(event) {
if (this.filteredUsers.length > 0) {
this.arrowCounter = event.code == "ArrowDown" ? ++this.arrowCounter : --this.arrowCounter;
if (this.arrowCounter >= this.filteredUsers.length)
this.arrowCounter = (this.arrowCounter) % this.filteredUsers.length;
else if (this.arrowCounter < 0)
this.arrowCounter = this.filteredUsers.length + this.arrowCounter;
this.setResult(this.filteredUsers[this.arrowCounter].text);
}
},
<input class="form-control bg-light-blue" id="SearchText" type="text" v-model="search"
#keydown.enter = 'enter'
#input = 'change'
#keyup="inputChanged"
#keydown.down="onArrow"
#keydown.up="onArrow"
/>
Example:- In the Flipkart website in the searchbar if i type shoes, and then if i go back and again click and search bar previously visited searched items will be saved in the searchbar.
I am looking for the same functionality in vuejs
I went to the Flipkart site and inspected their search input. It is an input tag combined with unordered list. So I created this sample component.
EDIT: Added logic to show/hide search history. Added history max length.
InputWithList.vue
<template>
<div class="input-with-list">
<h4>Input with List</h4>
<div class="row">
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" v-model="searchValue" #keyup.enter="processSearch"
#click="onClick" #input="onInput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" #click="processSearch">Search</button>
</div>
</div>
<div class="form-group">
<ul class="list-group" v-if="showSearchHistory">
<li class="list-group-item" v-for="(item, index) in searchHistory" :key="index"
#click="selectPreviousSearch(index)">{{ item }}</li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="button" class="btn btn-secondary" #click="clearHistory">Clear history</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchValue: '',
searchHistory: [],
showSearchHistory: false,
searchHistoryMaxLength: 5
}
},
methods: {
processSearch() {
if ( this.searchHistory.indexOf(this.searchValue) === -1) {
this.searchHistory.push(this.searchValue);
if (this.searchHistory.length > this.searchHistoryMaxLength) {
// Remove the first (oldest) element
this.searchHistory.shift();
}
}
this.searchValue = '';
},
selectPreviousSearch(index) {
this.searchValue = this.searchHistory[index];
this.showSearchHistory = false;
},
clearHistory() {
this.searchHistory = [];
this.searchValue = '';
},
onClick() {
// Toggle show/hide
this.showSearchHistory = !this.showSearchHistory;
},
onInput() {
this.showSearchHistory = false;
}
}
}
</script>
<style scoped>
li:hover {
background-color:gainsboro;
}
</style>

Change css display of multiple elements using class in javascript

Fairly new to Javascript here. I have a to do list, and I am in the process of adding a feature to Hide all checked items (which have a class .checked).
The idea i have, is to add a display property to the class(that all checked items receive) but how do I do it? Is there any other way for me to be able to add a display property to all of the checked items?
Here's the code (didn't include the other css as it was unnecesary):
//ADD NEW ELEMENT SECTION
function newElement() {
var inputval = document.getElementById('inputnewlist').value;
var li = document.createElement('li');
var lichild = document.createTextNode(inputval);
li.appendChild(lichild);
if (inputval === '') {
alert('you must put something in the textbox!');
} else {
document.getElementById('mylist').appendChild(li);
}
document.getElementById('inputnewlist').value = "";
//REMOVE BUTTON SECTION
var button = document.createElement('button');
var buttonval = document.createTextNode('x');
button.classList.add("exit");
button.appendChild(buttonval);
li.appendChild(button);
var exit = document.querySelectorAll('.exit');
for (b = 0; b < exit.length; b++) {
exit[b].addEventListener('click', removeButtonParent);
}
}//end of create newelement function
var exit = document.querySelectorAll('.exit');
for (z = 0; z < exit.length; z++) {
exit.addEventListener('click', removeButtonParent);
}
function removeButtonParent() {
event.target.parentElement.remove();
}
//ENTER KEY PRESS-BUTTON PRESS
function enterfunction(event) {
var key = document.getElementById('inputnewlist');
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('addbutton').click();
}}
//CHECK BUTTON SECTION
var list = document.querySelector('ul');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
//HIDE CHECKED LIST ITEMS
function hideCheck() {
if (event.target.checked === true) {
var checkLI = document.querySelectorAll('.checked');
checkLI.style.display = "none";
}
else {
var checkliELSE = document.querySelectorAll('.checked');
checkLI.style.display = "";
}
}
.checked {
background-color: darkgrey;
text-decoration: line-through;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div id="formcontainer">
<h1 class="title"> To Do List </h1>
<input type="text" name="inputnewlist" id="inputnewlist" placeholder="Add thing to do.." onkeydown="enterfunction(event)">
<button onclick="newElement()" class="addbutton" id="addbutton">Add</button>
</div>
<ul id="mylist">
</ul>
<input type="checkbox" id="hidecheck" onchange="hideCheck()"> <label for="hidecheck"> Hide the checked list items</label>
<script src="scripts.js"></script>
</body>
You can try the following code by adding the style 1 by 1.
function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}

[HTML DOM].style undefinded? (html5 app: address book)

so basically I can't figure out why is giving me the folling error, when I call add() function (when you click on add button)...
it says: status.style is undefined
status is an html dom, an html tag
I think the error is located almost at the end of the sheet
var myArray = []; // * used to store all the data
myArray[0] = ['John', 'Doe', '1980'];
myArray[1] = ['Jane','Malloy','1982'];
myArray[2] = ['Vincent','Malloy','1988'];
var firstName = document.getElementById('firstName');
var secondName = document.getElementById('secondName');
var bornYear = document.getElementById('bornYear');
var output = document.getElementById('output');
var form1 = document.getElementById('form1');
var status = document.getElementById('status');
var add = function() { //calls statusMessagge()
// check if input[] its not empty...
if ( firstName.value.length>0 && secondName.value.length>0 && bornYear.value.length>0 ) {
// * adding inputs to myArray
myArray[myArray.length] = [firstName.value ,secondName.value ,bornYear.value ];
//clearBoxes();
// * status messagge
statusMessagge('good');
alert('is good');
}
else {
statusMessagge('bad');
alert('is bad');
}
};
var statusMessagge = function(arg) { // * it is been called by: add(), show()
// * selecting the messagge to appear
switch (arg) {
case 'good':
status.innerHTML = 'Person added successfully.';
break;
case 'bad':
status.innerHTML = 'Please fill all the fields.';
break;
case 'loading':
status.innerHTML = 'Loading...';
break;
case 'loaded':
status.innerHTML = 'Finish.';
break;
}
// * do opacity effect slow: show|hide
status.style.opacity = 1; // this is the part that I get the error.
setTimeout (function() {
status.removeAttribute('style');
}, 1000);
};
body {
background: lightgray;
font-family: consolas;
font-size: 13px;
padding: 0;
margin: 0;
}
main {
background: #dbcdcd;
margin: 0 auto;
}
form:nth-of-type(1) {
float: left;
}
form:nth-of-type(2) {
float: left;
}
label { /* for alining elements correctly */
display: inline-block;
width: 77px;
text-align: right;
}
input[type="text"]:not(:first-of-type) {
margin-top: 5px;
}
#status {
opacity: 0;
transition: opacity .20s;
clear: both;
}
<!doctype html>
<html lang="es-ES">
<head>
<title>.:_My Exercise_:.</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<meta charset="utf-8"/>
</head>
<body>
<main>
<form id="form1" action=""> <!--action="#" onsubmit="return false"-->
<fieldset>
<legend>Please introduce new person...</legend>
<label>firstName:</label>
<input id="firstName" type="text" autofocus tabindex="1"/>
<input type="button" value="Add" onclick="add()"/> <br/>
<label>secondName:</label>
<input id="secondName" type="text" tabindex="2"/>
<input type="button" value="Show" onclick="show()"/> <br/>
<label>bornYear:</label>
<input id="bornYear" type="text" tabindex="3"/>
<input type="button" value="Sort" onclick="sort()"/>
</fieldset>
</form>
<form>
<fieldset>
<legend>Sort...</legend>
<input type="button" value="a-z" onclick=""/>
<input type="button" value="z-a" onclick=""/>
</fieldset>
</form>
<p id="status"></p>
<p id="output"></p>
</main>
<script src="script.js"></script>
</body>
</html>
I think that what you want is to display a message in console. Use console.log() for that. It worked in Firefox for me.
Example:
// ... (your previous code)
if ( firstName.value.length>0 && secondName.value.length>0 && bornYear.value.length>0 ) {
myArray[myArray.length] = [firstName.value ,secondName.value ,bornYear.value ];
console.log("good");
alert('is good');
}
else {
console.log("bad");
alert('is bad');
}
// ...
I passed the element through to the statusMessage function allowing me to set it's innerHTML value.
We get the elements on the time of click rather onload to prevent the variables to be undefined.
var myArray = []; // * used to store all the data
myArray[0] = ['John', 'Doe', '1980'];
myArray[1] = ['Jane','Malloy','1982'];
myArray[2] = ['Vincent','Malloy','1988'];
var add = function() { //calls statusMessagge()
var firstName = document.getElementById('firstName');
var secondName = document.getElementById('secondName');
var bornYear = document.getElementById('bornYear');
var output = document.getElementById('output');
var form1 = document.getElementById('form1');
var status = document.getElementById('status');
// check if input[] its not empty...
if ( firstName.value.length>0 && secondName.value.length>0 && bornYear.value.length>0 ) {
// * adding inputs to myArray
myArray[myArray.length] = [firstName.value ,secondName.value ,bornYear.value ];
//clearBoxes();
// * status messagge
statusMessage(status, 'good');
}
else {
statusMessage(status, 'bad');
}
};
var statusMessage = function(element, arg) { // * it is been called by: add(), show()
element.style.opacity = 1;
switch (arg) {
case 'good':
element.innerHTML = 'Person added successfully.';
break;
case 'bad':
element.innerHTML = 'Please fill all the fields.';
break;
case 'loading':
element.innerHTML = 'Loading...';
break;
case 'loaded':
element.innerHTML = 'Finish.';
break;
default:
element.innerHTML = "";
break;
}
// * do opacity effect slow: show|hide
setTimeout (function() {
element.removeAttribute('style');
}, 1000);
};
body {
background: lightgray;
font-family: consolas;
font-size: 13px;
padding: 0;
margin: 0;
}
main {
background: #dbcdcd;
margin: 0 auto;
}
form:nth-of-type(1) {
float: left;
}
form:nth-of-type(2) {
float: left;
}
label { /* for alining elements correctly */
display: inline-block;
width: 77px;
text-align: right;
}
input[type="text"]:not(:first-of-type) {
margin-top: 5px;
}
#status {
opacity: 0;
transition: opacity .20s;
clear: both;
}
<!doctype html>
<html lang="es-ES">
<head>
<title>.:_My Exercise_:.</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<meta charset="utf-8"/>
</head>
<body>
<main>
<form id="form1" action=""> <!--action="#" onsubmit="return false"-->
<fieldset>
<legend>Please introduce new person...</legend>
<label>firstName:</label>
<input id="firstName" type="text" autofocus tabindex="1"/>
<input type="button" value="Add" onclick="add()"/> <br/>
<label>secondName:</label>
<input id="secondName" type="text" tabindex="2"/>
<input type="button" value="Show" onclick="show()"/> <br/>
<label>bornYear:</label>
<input id="bornYear" type="text" tabindex="3"/>
<input type="button" value="Sort" onclick="sort()"/>
</fieldset>
</form>
<form>
<fieldset>
<legend>Sort...</legend>
<input type="button" value="a-z" onclick=""/>
<input type="button" value="z-a" onclick=""/>
</fieldset>
</form>
<p id="status"></p>
<p id="output"></p>
</main>
<script src="script.js"></script>
</body>
</html>
Different approach:
I run your code on chrome, with one difference: run script.js after event 'DOMContentLoaded', the event holds your script until browser informs that loaded all html:
document.addEventListener('DOMContentLoaded', function(){
var myArray = []; // * used to store all the data
myArray[0] = ['John', 'Doe', '1980'];
myArray[1] = ['Jane','Malloy','1982'];
myArray[2] = ['Vincent','Malloy','1988'];
var firstName = document.getElementById('firstName');
var secondName = document.getElementById('secondName');
var bornYear = document.getElementById('bornYear');
var output = document.getElementById('output');
var form1 = document.getElementById('form1');
var status = document.getElementById('status');
window.add = function() { //calls statusMessagge()
// check if input[] its not empty...
if ( firstName.value.length>0 && secondName.value.length>0 && bornYear.value.length>0 ) {
// * adding inputs to myArray
myArray[myArray.length] = [firstName.value ,secondName.value ,bornYear.value ];
//clearBoxes();
// * status messagge
statusMessagge('good');
alert('is good');
}
else {
statusMessagge('bad');
alert('is bad');
}
};
var statusMessagge = function(arg) { // * it is been called by: add(), show()
// * selecting the messagge to appear
switch (arg) {
case 'good':
status.innerText = 'Person added successfully.';
break;
case 'bad':
status.innerText = 'Please fill all the fields.';
break;
case 'loading':
status.innerText = 'Loading...';
break;
case 'loaded':
status.innerText = 'Finish.';
break;
}
// * do opacity effect slow: show|hide
status.style.opacity = 1; // this is the part that I get the error.
setTimeout (function() {
status.removeAttribute('style');
}, 1000);
};
});
In function statusMessagge() you assign status with string, so it isn't html element anymore.
Try do:
status.innerText = 'some text';

Categories

Resources