How can I avoid NaN and add & substract on OOP Javascript - javascript

I have a initial value of 10000 and I want to add or substract the initial value depending to the value I input. For example, I click the radio button name Add I want to disable the 2nd textBox. Enter a value into 1st textbox. Add the initial value and the value of textbox1. When I click the 2nd radio button name Minus I want to disable the 1st textBox minus 2nd textbox to initial value. OOP style. When I click the compute button it show the answer and back it to normal so I can choose and enter another number add it to table.
//external script
function Compute(initialNum, numOne, numTwo) {
this._initialNum = initialNum; // 10000
this._numOne = numOne; //input by user
this._numTwo = numTwo; //input by user
this.addNum = function() {
this._initialNum = this._initialNum + this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = this._initialNum - this._numTwo;
return this._initialNum;
};
}
//JavaScript in <body>
var initialValue = 10000;
var numOne = parseInt(document.getElementById('txtNumOne'));
var numTwo = parseInt(document.getElementById('txtNumTwo'));
var rdoAdd = document.getElementById("rdoAdd").value;
var rdoMinus = document.getElementById("rdoMinus").value;
var tblResult = document.getElementById("tblResult");
function disableTxtAdd() {
if(rdoAdd == "rdoAdd") {
document.getElementById("txtNumTwo").disabled = true;
}
else{
document.getElementById("txtNumTwo").disabled = false;
}
}
function disableTxtMinus() {
if(rdoMinus == "rdoMinus") {
document.getElementById("txtNumOne").disabled = true;
}
else{
document.getElementById("txtNumOne").disabled = false;
}
}
function print() {
var objAccount = new Compute(initialValue, numOne.value, numTwo.value);
var display = "";
if(rdoAdd.checked)
{
display += "<tr>";
display += "<td>" + objAccount.addNum() + "</td>";
display += "<tr>";
tblResult.innerHTML = display;
} else {
display += "<tr>";
display += "<td>" + objAccount.minusNum() + "</td>";
display += "<tr>";
tblResult.innerHTML = display;
}
}
<input name = "operation" type = "radio" id = "rdoAdd" value = "rdoAdd" onclick = "disableTxtAdd()">Add<br><br>
<input name = "operation" type = "radio" id = "rdoMinus" value = "rdoMinus" onclick = "disableTxtMinus()">Minus<br><br>
Deposit:<br><br>
<input type = "text" id = "txtNumOne"><br><br>
Withdraw<br><br>
<input type = "text" id = "txtNumTwo">
<button onclick = "print()">Compute</button><br><br>
<table border = "1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angelica's calculator</title>
<script>
// When the Add button is clicked
function disableTxtAdd() {
document.getElementById("txtNumTwo").disabled = true;
document.getElementById("txtNumOne").disabled = false;
}
// When the Minus button is clicked
function disableTxtMinus() {
document.getElementById("txtNumOne").disabled = true;
document.getElementById("txtNumTwo").disabled = false;
}
// When the Compute button is clicked
function print(){
var initialValue = 10000;
var numOne = document.getElementById('txtNumOne').value;
var numTwo = document.getElementById('txtNumTwo').value;
var tblResult = document.getElementById("tblResult");
var display;
var result;
if(document.getElementById("txtNumTwo").disabled){
// Add input value to 10000
if(Number.isInteger(parseInt(numOne))){
result = initialValue + parseInt(numOne);
}else{
result = "Enter a number";
}
display = "<tr><td>" + result + "</td><tr>";
tblResult.innerHTML = display;
}else if(document.getElementById("txtNumOne").disabled){
// Subtract input from 10000
if(Number.isInteger(parseInt(numTwo))){
result = initialValue - parseInt(numTwo);
}else{
result = "Enter a number";
}
display = "<tr><td>" + result + "</td><tr>";
tblResult.innerHTML = display;
}
// Enable both inputs
document.getElementById("txtNumTwo").disabled = false;
document.getElementById("txtNumOne").disabled = false;
// Empty the inputs
document.getElementById("txtNumTwo").value = "";
document.getElementById("txtNumOne").value = "";
}
</script>
</head>
<body>
<input name="operation" type="radio" id="rdoAdd" value="rdoAdd" onclick="disableTxtAdd()">Add<br><br>
<input name="operation" type="radio" id="rdoMinus" value="rdoMinus" onclick="disableTxtMinus()">Minus<br><br>
Deposit:<br />
<input type="text" id="txtNumOne"><br /><br />
Withdraw<br />
<input type="text" id="txtNumTwo"><br /><br />
<button onclick="print()">Compute</button><br /><br />
<table border="1px" style="border-collapse:collapse";>
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
</body>
</html>

Related

Session storage value showing null

I keep on getting null every time I try to store values in Section B and C but works fine for A. I can't seem to find where the issue is. I am trying to have a user's info display on a different page based on the section he chooses. If the user chooses section B for example I would want to let the user know on the next page that he/she has ordered a seat in Section B and whatever the available seat is along with the name and price. After the boarding pass is displayed on the next page, I want the array to change from having 5 seats to 4 and keep this array updated everytime a new person signs up.
index.html
<!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>
<script src = "airplane.js"></script>
</head>
<style>
</style>
<body>
<h1>Welcome To Air France</h1>
<h2>Choose your seat section here</h2>
<h3>Section A</h3>
<p>Price:</p>
<div id = "Section1Price"></div>
<div id = "Section1"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameA" type="text" size="25" height="25">
<input id = "bookSeatA" type="button" onclick="location.href='bookingPage.html';" value="Book a Seat in Section A" />
</form>
<h3>Section B</h3>
<p>Price:</p>
<div id = "Section2Price"></div>
<div id = "Section2"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameB" type="text" size="25" height="25">
<input id = "bookSeatB" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section B">
</form>
<h3>Section C</h3>
<p>Price:</p>
<div id = "Section3Price"></div>
<div id = "Section3"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameC" type="text" size="25" height="25">
<input id = "bookSeatC" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section C">
</form>
</body>
</html>
airplane.js
function start()
{
var price1;
price1 = Math.random() * (200 - 100) + 100;
price1 = price1.toFixed(2);
var price2 = (Math.random() * (300 - 100) + 100).toFixed(2);
var price3 = (Math.random() * (300 - 100) + 100).toFixed(2);
var priceArray = [price1, price2, price3];
var sectionASeats = [];
var sectionBSeats = [];
var sectionCSeats = [];
for (var k = 0; k < 5; k++)
{
sectionASeats[k] = 0;
sectionBSeats[k] = 0;
sectionCSeats[k] = 0;
}
var buttonA = document.getElementById( "bookSeatA" );
buttonA.addEventListener( "click", function() {bookSeat(sectionASeats)}, false );
buttonA.addEventListener("click",function(){handleSubmitA(priceArray[0],sectionASeats,"A")}, false );
var buttonB = document.getElementById( "bookSeatB" );
buttonB.addEventListener( "click", function() {bookSeat(sectionBSeats)}, false );
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
var buttonC = document.getElementById( "bookSeatC" );
buttonC.addEventListener( "click", function() {bookSeat(sectionCSeats)}, false );
buttonC.addEventListener("click",function(){handleSubmitC(priceArray[2]),sectionCSeats,"C"}, false );
var result1 = "";
var result2 = "" ;
var result3 = "" ;
result1 += checkSection(sectionASeats, "A" );
result2 += checkSection(sectionBSeats, "B" );
result3 += checkSection(sectionCSeats, "C" );
priceArray.sort(function(a,b) {return a-b});
document.getElementById("Section1Price").innerHTML = "$" + priceArray[0];
document.getElementById("Section1").innerHTML = result1;
document.getElementById("Section2Price").innerHTML = "$" + priceArray[1];
document.getElementById("Section2").innerHTML = result2;
document.getElementById("Section3Price").innerHTML ="$" + priceArray[2];
document.getElementById("Section3").innerHTML = result3;
}
function sectionSeatNum (array)
{
for (var i = 0; i < array.length;i++)
{
if (array[i] == 1)
{
return i+1;
}
}
}
function handleSubmitA(priceForA,array,section)
{
const name = document.getElementById("clientNameA").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForA);
return;
}
function handleSubmitB(priceForB,array,section)
{
const name = document.getElementById("clientNameB").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForB);
return;
}
function handleSubmitC(priceForC,array,section)
{
const name = document.getElementById("clientNameC").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForC);
return;
}
function bookSeat(array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == 0)
{
array[i] = 1;
break;
}
}
}
function checkSection(array, section)
{
var result;
var check = true;
var emptyCounter = 0;
var takenCounter = 0;
for (var i = 0;i<array.length;i++)
{
if(array[i] == 0)
{
emptyCounter++;
}
else{
takenCounter++;
}
}
if(takenCounter == array.length)
{
check = false;
result = "<p>There are no seats available in Section " + section + ".</p>";
}
else{
check = true;
result = "<p>There are " + emptyCounter + " seats available in Section " + section + ".</p>";
}
return result;
}
window.addEventListener("load", start,false);
bookingPage.html
<!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>
<script src = "booking.js"></script>
</head>
<body>
<h1>Thank you for choosing Air France</h1>
<h2>Here is your boarding pass</h2>
<h3 id="booking-name"></h3>
<form action="index.html" method="get">
<input id = "backToHome" type="button" onclick="location.href='index.html';" value="Return to Homepage">
</form>
</body>
</html>
booking.js
function start()
{
const name = sessionStorage.getItem("NAME");
const price = sessionStorage.getItem("PRICE");
const arrayBookings = JSON.parse(sessionStorage.getItem("ARRAY"));
const section = sessionStorage.getItem("SECTION");
var seatNum = sessionStorage.getItem("SEATNUM")
var result = "";
result += "<p> Thank you " +name+ " for flying with us. Here is your boarding pass.</p>";
result += "<p> Name: " + name + "</p>";
result += "<p> Section: "+ section + "</p>";
result += "Price: $"+price;
result += "<p>Seat number: "+seatNum+ "</p>";
// result += "<p>"+arrayBookings+"</p>";
document.getElementById("booking-name").innerHTML = result;
}
window.addEventListener("load", start, false);
You have typo here
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
while you want to have
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1],sectionBSeats,"B")}, false );
Session C is the same error.

JavaScript arrays adding last element instead of recently added input

Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}

How to clear all dynamically created SPAN elements

I've created some code that dynamically creates some fields within a SPAN element. One of the fields is a delete icon, that when click runs a function to remove the selected span. Now I want to create a function that simply wipes out all the spans, sounds simple but it breaks after the first one.
This is a sample of my code (modified it for simplicity):
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ip = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ip.setAttribute("type", "text");
ip.setAttribute("value", item)
ip.setAttribute("Name", "text_item_element_" + global_i);
ip.setAttribute("id", "id_item_" + global_i);
ip.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ip);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
In each line for the image I set the onclick event handler to run the function removeSpanElement(parentDiv, childDiv) and it works fine. So to clear them all I'd think I just run the function through an incremental loop, clearItems(), but it stops after removing the first one and I can't figure out why.
You can simply add a new class to the dynamically added span(to make it easy to select them), then remove all the elements with the added class like
var global_i = 0; // Set Global Variable i
function increment() {
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem() {
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ins = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ins.setAttribute("type", "text");
ins.setAttribute("value", item);
ins.setAttribute("Name", "text_item_element_" + global_i);
ins.setAttribute("id", "id_item_" + global_i);
ins.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ins);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
el.className = 'dynamic'
document.getElementById("myForm").appendChild(el);
}
/* This function only clears 1st span */
function clearItems() {
var spans = document.getElementsByClassName('dynamic');
while (spans.length) {
spans[0].remove();
}
global_i = 0;
}
<form>
<input type='text' id='item' value='' />
<input type="button" value="Add" onclick="addItem()" />
<input type="button" value="Clear All" onclick="clearItems()" />
<span id="myForm"></span>
</form>
You were using a reserved keyword, and you were having a variable undefined. I've edited the code for you. Compare my code with yours to see where are the mistakes.
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem(){
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ig = document.createElement("INPUT"); // "in" is a reserved keyword. It can't be used as a variable
var ip = document.createElement("IMG");
var el = document.createElement('SPAN');
ig.setAttribute("type", "text"); // modified
ig.setAttribute("value", item) //
ig.setAttribute("Name", "text_item_element_" + global_i); //
ig.setAttribute("id", "id_item_" + global_i); //
ig.setAttribute("style", "width:80px"); //
ig.setAttribute("src", "delete.png"); // "im" was undefined. You probably wanted to write "in", but it was wrong anyway
ig.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')"); // the same
el.appendChild(ig);
el.appendChild(ig);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
<code> <form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
try{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var in_e = document.createElement("INPUT");
var ip_e = document.createElement("IMG");
var el = document.createElement('SPAN');
in_e.setAttribute("type", "text");
in_e.setAttribute("value", item)
in_e.setAttribute("Name", "text_item_element_" + global_i);
in_e.setAttribute("id", "id_item_" + global_i);
in_e.setAttribute("style", "width:80px");
ip_e.setAttribute("src", "delete.png");
ip_e.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(in_e);
el.appendChild(in_e);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}catch(e){alert(e)}
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
</code>

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources