Javascript: Labeling array results - javascript

Alright so here is my Html code:
<html>
<head>
<title>Planning</title>
<script type="text/javascript" src="Function.js"></script>
</head>
<body>
<form id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="Name">Name:</label> <input id="Name" type="text" />
<br>
<label for="Date">Date: </label><input id="Date" type="text" />
<br>
<label for="Plans">Plans: </label><input id="Plans" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show data" onclick="show();"> <br>
<h2><b>Data:</b></h2>
<hr>
</form>
<div id="display">
</div>
</body>
</html>
And my Javscript:
var Name=new Array();
var Date=new Array();
var Plans=new Array();
function insert(){
var NameValue = document.getElementById('Name').value;
var DateValue = document.getElementById('Date').value;
var PlansValue = document.getElementById('Plans').value;
Name[Name.length]=NameValue;
Date[Date.length]=DateValue;
Plans[Plans.length]=PlansValue;
}
function show() {
var content="<b>Your Plans For the Day:</b><br>";
var Namelabel ="<p>Name</p>"
for(var i = 0; i < Name.length; i++) {
+ Namelabel;
content +=Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content +=Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content +=Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
The code on its own works fine but what I for the life of me can't figure out how to do is add a label identifying what the data showed is.
example being "Name:" for the displayed names and "dates:" appearing before the displayed dates.
I have other parts of the document I need to do in the meantime but this is really bothering me.

Change you show function to this
function show() {
var content="<b>Your Plans For the Day:</b><br>";
for(var i = 0; i < Name.length; i++) {
content += "Name " + Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content += "Date" + Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content += "Plans" + Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}

Related

new input replace Instead of append

Here is the html that I wrote for program
It's working but append is not working.
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6 justify-content-center">
<span>Full Name :</span>
<input id="name" type="name" class="d-flex mb-3">
<span>Email :</span>
<input id="email" type="email" name="email" class="d-flex mb-3">
<span>Comment :</span>
<input id="comment" type="text" class="d-flex mb-3">
<button id="btn" class="mt-3">Submit</button>
</div>
<div class="col-md-6">
<p id="demo"></p>
</div>
</div>
</div>
name and comment are inputs.
I type some text but append doesn't working and the new text that entered replace the first one.
function SubmitComment(name, comment) {
let newComment = censor(comment)
for (let i = 0; i < name.length; i++) {
let demo = $("#demo");
demo.html("")
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "swan") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Am not sure why your looping the name property, but here is a working example!
function Submit() {
SubmitComment($('.name'), $('.comment'));
}
function SubmitComment(name, comment) {
let newComment = censor(comment)
let demo = $("#demo");
demo.html("")
for (let i = 0; i < name.length; i++) {
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "kilt") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="name" />
<input class="comment" />
<button onClick="Submit()">Submit</button>
<div id="demo"></div>

Loading user input into an array then display

Trying to get user input from HTML form and then get it into an array in javascript. Afterwards output it back into the div tag in HTML as a list.
The code works but it outputs the text twice instead of just once.
Example: user inputs orange in HTML form, then inputs apple, then banana
My code makes it output: orange, orange, apple, orange, apple, banana
It should just output: orange, apple, banana
// global variable
var enteredStringsArray = [];
function listArray() {
"use strict";
var form;
var enteredText;
var enteredString;
var index;
form = document.getElementById("lab06");
enteredText = form.text.value;
enteredStringsArray.push(enteredText);
enteredString = document.getElementById("theOrderedList");
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + " </li>";
}
return false;
}
<form id="list" action="#" onsubmit="return listArray();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>
replace
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + "
</li>";
}
from
enteredString.innerHTML += "<li>" + enteredText + "</li>";
it will work. Add each input items one by one. no need to loop it.
You can try without forloop, just create new li element and append in your ol
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>
EDIT:
With forloop:
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
//console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
for (var i= enteredStringsArray.length - 1; i < enteredStringsArray.length; i++)
{
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
}
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>

how to turn asterisk red when field is left blank?

I am trying iterate through a simple form with four elements, and only three are required elements. How do I turn the asterisk red when a required element is left blank?
Here's the code which is not working, and I'm not certain how to make it work.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<style type='text/css'>
</style>
</head>
<body>
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><span class="asterisk">*</span> required</p>
<p><span class="asterisk">*</span> <label>First Name:<br><input type="text" name="firstName"></label></p>
<p><label>Last Name:<br><input type="text" name="lastName"></label></p>
<p><span class="asterisk">*</span> <label>Email:<br><input type="email" name="email"></label></p>
<p><span class="asterisk">*</span> <label>Gender:<br><input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female</label></p>
<p><input type="submit" value="Submit"></p>
</form>
<script>
var formy = document.getElementById('myForm');
var required_inputs = ['firstName', 'email', 'gender'];
formy.onsubmit = function(event) {
for (var i = 0; i < required_inputs.length; i++) {
var input = this[required_inputs[i]];
if (input.value.length == 0) {
event.preventDefault();
document.getElementsByClassName('asterisk').color('#FFCCC');
}
}
}
</script>
</body>
</html>
In your code replace document.getElementsByClassName('asterisk').color('#FFCCC'); with
var ele = document.getElementsByClassName('asterisk');
for (var j = 0; j < ele.length; i++ ) {
ele[j].style.color = "red";
}
Or single line (Array.From):
Array.from(document.querySelectorAll(".asterisk"), e => e.style.color = "red");
Updated code:
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><span class="asterisk">*</span> required</p>
<p><span class="asterisk">*</span> <label>First Name:<br><input type="text" name="firstName"></label></p>
<p><label>Last Name:<br><input type="text" name="lastName"></label></p>
<p><span class="asterisk">*</span> <label>Email:<br><input type="email" name="email"></label></p>
<p><span class="asterisk">*</span> <label>Gender:<br><input type="radio" name="gender" value="male" class="gender">Male
<input type="radio" name="gender" value="female" class="gender">Female</label></p>
<span id="error" style="display:none;color:red;">Gender is required</span>
<p><input type="submit" value="Submit"></p>
</form>
<script>
var formy = document.getElementById('myForm');
var required_inputs = ['firstName', 'email', 'gender'];
formy.onsubmit = function (event) {
event.preventDefault();
document.getElementById("error").style.display = "none";
for (var i = 0; i < required_inputs.length; i++) {
var input = this[required_inputs[i]];
if (input.tagName != undefined) { //input text fields
input.style.removeProperty('border');
if (input.value.length == 0) {
input.style.borderColor = "red";
var ele = document.getElementsByClassName('asterisk');
for (var j = 0; j < ele.length; j++) {
ele[j].style.color = "red";
}
}
}
else { //for radio button
var el = document.getElementsByClassName(required_inputs[i]);
var checked = false;
for (var j = 0; j < el.length; j++) {
if (el[j].checked) checked = true;
}
if (!checked)
{
document.getElementById("error").style.display = "block";
var ele = document.getElementsByClassName('asterisk');
for (var j = 0; j < ele.length; j++) {
ele[j].style.color = "red";
}
}
}
}
}
</script>

Creating inputs in function, or any other method (Javascript)

I'm trying to make something that makes it easier to write out a matrix/matrices.
You start with getting two number inputs for the dimensions of the matrix. And after that you "submit" the numbers and out comes several input boxes.
How do you write this code? Is it possible to do it in another function?
I was thinking of having the "submit" button have a validification to see if numbers are real, and if they are the function continues with for loops on how to "write" out the number boxes.
This is what I got right now:
function validate(){
var num;
num = document.getElementById("numberbox").value;
var myForm = document.getElementById('payForm'); //
while(myForm.hasChildNodes()){
myForm.removeChild(myForm.firstChild);
}
myForm = document.createElement("form");
myForm.setAttribute("method","post");
myForm.setAttribute("action","processChecking.php");
if(isNaN(num) || num<1){
document.getElementById("output").innerHTML = "invalid number!";
document.getElementById("numberbox").value = '';
} else {
document.getElementById("output").innerHTML = "number validated!";
array(num);
for (var i = 0; i <= num; i++) {
var input = document.createElement('input');
input.type = 'text';
input.name = 'myInput_' + i;
input.id = 'myInput_' + i;
myForm.appendChild(input);
}
}
}
<body>
<table>
<tr>
<td>
<p>
Enter number for how many number boxes you want:<br>
<input id="numberbox" type="number">
<button type="button" onclick="validate()">Validate</button>
<br>
<p id="output"></p>
<br>
</p>
</td>
<td style="text-align:right;">
<p id="payForm"></p>
</td>
</tr>
</table>
</body>
Here is what I made from your question so far. If it is on track, then we can build upon it.
function createTable() {
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var theader = '<table border="1">\n';
var tbody = '';
for (var i = 0; i < num_rows; i++) {
tbody += '<tr>';
for (var j = 0; j < num_cols; j++) {
tbody += '<td>';
tbody += '<input type="number">'
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
<form name="tablegen">
<label>Input number of rows :
<input type="number" name="rows" id="rows" />
</label>
<br />
<label>Input number of columns :
<input type="number" name="cols" id="cols" />
</label>
<br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();' />
</form>
<div id="wrapper"></div>

there are two html pages. I want the data status of first pages to saved when I reverting from next page to first page

When I click on back button of next page the check box value should not be reset.
It should be same as I checked or unchecked. The code from the first and next page is below.
First Page
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" name="code" value="ECE">ECE<br>
<input type="checkbox" name="code" value="CSE">CSE<br>
<input type="checkbox" name="code" value="ISE">ISE<br>
<br>
<input type="button" onclick="dropFunction()" value="save">
<br><br>
<script>
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
</script>
</form>
</body>
</html>
Next Page
<html>
<head>
<title>Welcome to </title>
</head>
<body color="yellow" text="blue">
<h1>welcome to page</h1>
<h2>here we go </h2>
<p> hello everybody<br></p>
</body>
<image src="D:\images.jpg" width="300" height="200"><br>
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.location.href="first.html";
}
</script>
</body>
</html>
Full solution: example. First add ids to your checkboxes:
<input type="checkbox" name="code" value="ECE" id='1'>ECE<br>
<input type="checkbox" name="code" value="CSE" id='2'>CSE<br>
<input type="checkbox" name="code" value="ISE" id='3'>ISE<br>
<input id="spy" style="visibility:hidden"/>
Then change your dropFunction:
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
localStorage.clear();
for (var i = 0; i < branch.length; i++)
if (branch[i].checked == true)
localStorage.setItem(branch[i].id, true);
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
And add some new javascript code to first.html:
window.onload = function() {
var spy = document.getElementById("spy");
if(spy.value=='visited')
for(var i=1;i<=3;i++)
if(localStorage.getItem(i))
document.getElementById(i).checked=true;
spy.value = 'visited';
}

Categories