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

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';

Related

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Trying to get values from multiple inputs

I'm trying to make a very basic expense tracker by building off the foundation of a todo app with vanilla Javascript. I'm having trouble isolating the value of all three input bars and getting them to display on the page. At the moment I'm getting 3 [objectHTMLInputElement] and undefined. I'd just like to know if I'm on the right track or if there's an easier way to isolate multiple input values and get them to display on the page. If somebody could point me in the right direction that'd be awesome. Thanks!
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = [
]
function add() {
let inputs = inputAll.value;
if (inputs == '') {
return true;
}
expenses.push(inputs);
displayExpenses();
}
function remove() {
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName}${inputDate}${inputAmount}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
* {
padding: 0;
box-sizing: border-box;
}
.headings {
text-align: center;
}
.headings h1 {
font-size: 3rem;
font-family: 'Courier New', Courier, monospace;
}
.headings h2 {
margin-top: -20px;
}
form {
text-align: center;
}
#input-name {
width: 50%;
}
#input-date {
width: 18%;
margin-right: 160px;
}
#input-amount {
width: 18%;
margin-left: 18px;
}
#add-btn {
margin-top: 50px;
margin-left: 800px;
}
<!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="style.css">
<title>Expense Tracker</title>
</head>
<body>
<div class="headings">
<h1>Expense Tracker</h1>
<h2>Add A New Item</h2>
</div>
<form>
<label>Name:</label>
<input class="input-all" id="input-name">
<br>
<br>
<label>Date:</label>
<input class="input-all" id="input-date">
<label>Amount:</label>
<input class="input-all" id="input-amount">
</form>
<button id="add-btn">Add Expense</button>
<ul id="expenses-ul"></ul>
<script src="main.js"></script>
</body>
</html>
Try this
const btn = document.getElementById('btn');
btn.addEventListener('click', function (event) {
const form = document.getElementById('form');
const output = document.getElementById('output');
const data = Object.fromEntries(new FormData(form).entries());
output.innerHTML = JSON.stringify(data, undefined, 2);
});
.wrap{
display: flex;
}
#output{
margin-left:50px;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding:5px;
min-width: 150px;
min-height: 80px;
}
<div class="wrap">
<div>
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="date">Date:</label><br>
<input type="text" id="role" name="role"> <br>
<label for="lname">Amount:</label><br>
<input type="text" id="amount" name="amount"><br><br>
<input id="btn" type="button" value="Print all value">
</form>
</div>
<div>
<pre id="output">
</pre>
</div>
</div>
When using document.querySelectorAll it's return a [NodeList] that consists of all selected elements on the other side there's also document.getElementsByClassName that return [HTMLCollection] - whatever you used you need to loop through to get the value of every selected input
When you passed [HTMLInputElement] as innerHTML of expensesUl it's will return the element object name not the value of this element because you are not selected any property of this object so you can't set an object as innerHTML of html element
if you want the right way of this part it's will be like that
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let expensesUl = document.getElementById('expenses-ul');
//this will give you empty string because they aren't get a value yet
expensesUl.innerHTML = `name = ${inputName.value}, date = ${inputDate.value}, amoute = ${inputAmount.value}`;
but now because we are selected all elements we are not need to select every input one by one anymore we will make a loop so we will loop through inputAll var to get the value of [HTMLInputElement] object
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
}
displayExpenses(inputAll);
}
function displayExpenses(elements) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < elements.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = elements[i].value
expensesUl.appendChild(expensesLi);
}
}
at the example above i removed expenses array but if you want to use it to take the value of the inputs you can make it like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
expenses.push(i.value)
}
displayExpenses(expenses);
}
function displayExpenses(values) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < values.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = values[i]
expensesUl.appendChild(expensesLi);
}
}
the whole code should to be like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
function add() {
for(var i of inputAll) {
if (i.value == '') {
return true
}
expenses.push(i.value)
}
displayExpenses();
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName.value}, ${inputDate.value}, ${inputAmount.value}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
about document.getElementsByClassName, document.querySelectorAll one deferant is that you can use array methods like forEach() with document.querySelectorAll while you can't do that with document.getElementsByClassName

storing array of objects ang then check previous and next item

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

How can I store and show data in array at the same time?

I want to make a simple guessing game by JavaScript. I want to make a guessing game where people can guess number against of random number. each time after guessing, it will store the result in a array, and show on right side of previous history.
//here is the JS file
var a=[10];
let x=0;
function check()
{
var num=Math.floor(Math.random()*5);
var a= document.getElementById("inpt").value;
if (num==a)
{
document.querySelector("#result").innerHTML="You are right in guess";
a[x]=true;
}
else {
document.querySelector("#result").innerHTML="You are Wrong in guess";
a[x]=false;
}}
if (a[x]==true)
{
document.getElementById("finalize").innerHTML=x+1+": number turn is right";
}
else{
document.getElementById("finalize").innerHTML=x+1+": number turn is wrong";
}
<!-- Here is the HTML file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My gussing game</title>
<script src="index.js"></script>
</head>
<body>
<div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
<H1>Game Input</H1>
<hr>
<input type="number" id="inpt" placeholder="Guess the number">
<br>
<button onclick="check()">Submit</button>
<p id="result"></p>
</div>
<div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
<h1>Game Result</h1>
<hr>
<p id="finalize"></p>
</div>
</body>
</html>
I can not understand why my code is not running!! can you please brief all the thing me?
you redeclare var a in check function, so assignment a[x] is for local var
If you format your code you will see that the field you want to update is outside of the check function:
var a = [10];
let x = 0;
function check() {
var num = Math.floor(Math.random() * 5);
var a = document.getElementById("inpt").value;
if (num == a) {
document.querySelector("#result").innerHTML = "You are right in guess";
a[x] = true;
}
else {
document.querySelector("#result").innerHTML = "You are Wrong in guess";
a[x] = false;
}
}
if (a[x] == true) {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
}
else {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
}
To perform that action everytime you submit a guess you need to move those fields inside of that function:
var a = [10];
let x = 0;
function check() {
var num = Math.floor(Math.random() * 5);
var a = document.getElementById("inpt").value;
if (num == a) {
document.querySelector("#result").innerHTML = "You are right in guess";
a[x] = true;
}
else {
document.querySelector("#result").innerHTML = "You are Wrong in guess";
a[x] = false;
}
if (a[x] == true) {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
}
else {
document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
}
}
Is this the sort of behaviour you want? (If it is then I will make comments in the code to explain)
Demo:
//here is the JS file
//array to hold each guess:
var guesses = [];
//number to hold current guess number (could also use guesses.length):
let x = 0;
//random number rounded to a whole number:
var num = Math.round(Math.floor(Math.random()*5),0);
function check(){
//for testing output the random num:
console.log(num)
if (x == 0){
//rest our message log div:
document.getElementById("finalize").innerHTML = ""
}
//get the current guess:
var a = document.getElementById("inpt").value;
//if guess equals random num:
if (num==a){
document.querySelector("#result").innerHTML="You are right in guess";
//push the current guess onto the guesses array:
guesses.push(a);
//update the div (<div id="guessArr"></div>) to hold a stringified representation
//of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
//create a p tag (<p></p>) to store our message
var p = document.createElement('p')
//add the message to that p tag:
p.innerHTML = x+1+": number turn is right"
//append it to the div:
document.getElementById("finalize").appendChild(p)
//reset our guess number/count:
x = 0;
//reset our guesses array:
guesses = [];
//reset our input field:
document.getElementById("inpt").value = "";
//generate a new random number to guess:
num = Math.round(Math.floor(Math.random()*5),0);
}
//if guess was incorrect:
else {
document.querySelector("#result").innerHTML="You are Wrong in guess";
//push the current guess onto the guesses array:
guesses.push(a);
//update the div (<div id="guessArr"></div>) to hold a stringified representation
//of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
//create a p tag (<p></p>) to store our message
var p = document.createElement('p')
//add the message to that p tag:
p.innerHTML = x+1+": number turn is wrong"
//append it to the div:
document.getElementById("finalize").appendChild(p)
//add one to our guess number/count:
x += 1;
}
}
<!-- Here is the HTML file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My gussing game</title>
<script src="index.js"></script>
</head>
<body>
<div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
<H1>Game Input</H1>
<hr>
<input type="number" id="inpt" placeholder="Guess the number">
<br>
<button onclick="check()">Submit</button>
<p id="result"></p>
</div>
<div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
<h1>Game Result</h1>
<hr>
<div id="guessArr"></div>
<div id="finalize">
</div>
</div>
</body>
</html>

How can I concat the content of dynamic textboxes to a single variable?

Here is the file (test.php) than I try to run on my localhost. Javascript works and it creates the text boxes. PHP-part does not work and makes problem.
<html>
<head>
<title>Test</title>
<script>
function newCheckbox() {
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElemenById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num) {
var elm = null;
try {
elm=document.createElement('<input type="checkbox" class="chk">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.className='chk';
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
var chbox = document.form1.getElementsByClassName('chk');
for(var i = 0; i<texts.length-1; i++){
if(chbox[i].checked){
chbox[i].parentNode.removeChild(chbox[i]);
texts[i].parentNode.removeChild(texts[i]);
}
}
}
</script>
<?php
$text_0= $_POST['text[0]'];
echo $text_0;
$textboxes = array();
for($i = 0;$i<count($_POST['text[]']); $i++)
{
$textboxes = $_POST['text'][$i];
}
$data=$textboxes
?>
</head>
<body>
<form action="test.php" name="form1" method="post">
<div>
<label>Checkbox text:<input type="text" name="text[]"></label><br>
<input type="button" onclick="newCheckbox();"value="add">
<input type="button" value="Delete" onclick = "delBoxes();" />
</div>
</form>
</body>
</html>
When I run the code I have the following problem
Undefined index: text[0]
Undefined index: text[]
I appreciates your help.

Categories

Resources