Display JSON list from dynamically created list - javascript

Alright, so I have not worked with JSON before. So far I am able to display the last information entered, but I need to display each input that is entered. How can I loop through my current function to do this? Would I need to do a for loop? If so, could I get some tips on how that would look? Any help would be great!
EDIT: The code is long so I inserted my codepen link here
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = submitForm;
var add = document.getElementsByClassName("add");
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var smoker = document.getElementsByName("smoker")[0];
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
var h2 = document.createElement("h2");
h2.appendChild(document.createTextNode("House Member List"));
ul.appendChild(h2);
function houseList() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (age.value == age.max) {
alert("Age must be 120 years old or less!");
return false;
} else if (dropDown.value == "") {
alert("Please choose a relationship");
return false;
} else {
var li = document.createElement("li");
if (smoker.checked) {
li.appendChild(
document.createTextNode(
dropDown.value + " " + age.value + ", Smoker " + " "
)
);
} else {
li.appendChild(
document.createTextNode(
dropDown.value + " " + age.value + ", Non-Smoker " + " "
)
);
}
li.setAttribute("id", "item" + lastId);
ul.appendChild(li);
var remove = document.createElement("button");
remove.appendChild(document.createTextNode("delete"));
remove.onclick = removeItem;
remove.setAttribute("onclick", 'removeItem("' + "item" + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
}
function removeItem(itemid) {
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
// THE CODE IN QUESTION
function submitForm() {
var display = document.getElementsByClassName("debug")[0];
var members = new Object();
members.Member = dropDown.value;
members.Age = age.value;
members.Smoker = smoker.checked;
var jsonText = JSON.stringify(members);
display.textContent = jsonText;
console.log(jsonText);
alert("Form has been submitted!");
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>

Related

How to get out the date validation to another separate function

I want to take out the date validation(a validation to my code to validate year between 1930 and the current year and if it's not correct it should print an error) to another separate new function, Instead of the Addmovie function.
i want to make another new function called datevalidation and I want to add date validation, which is currently in the addmovie function.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Week 07 Pass Submission</title>
<script src="./w7p.js"></script>
</head>
<body>
<header>
<h1>Week 07 Pass Submission</h1>
</header>
<article>
<form>
<label for="movie">Movie title</label>
<input type="text" id="movie" /><br /><br />
<span id="yearValidation" style="color: red"></span>
<br />
<label for="year">Release year</label>
<input type="text" id="year" /><br /><br />
<input type="button" id="add" value="Add">
<input type="button" id="show" value="List All">
</form><br />
<div style="padding-left: 20px;" id="list"></div>
</article>
</body>
</html>
JavaScript Code
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year');
var year = document.getElementById('year').value;
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
} else {
document.getElementById('yearValidation').innerHTML = '';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
You can declare a separate function dateValidation() and call it inside addMovie()
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function dateValidation(year,currentYear){
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year').value;
dateValidation(year,currentYear);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;

Javascript and HTML: doesnt show validation alert message upon clicking submit

I have problem with coding html and js. the alert is not appearing upon submitting and i was following the template entirely. Anyone are able to find what is the problem? im sure my script file is in the same directory and the file is linked after i had tested by using document.write(""). And also what i wish the web page to do is to alert(gErrorMsg).
This is the html part
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="" validate="novalidate">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>
this is the Javascript part
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent;
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList;
}
return selected;
}
This is your issue: you're using some undefined variables. Double check your HTML or if the variable is initialized.
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList; // ERROR: unitList is undefined
}
return selected;
}
Working Demo
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(e){
e.preventDefault(); // Necessary for some reason...
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = ""; //labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n"; // + unitList; // ERROR: unitList is undefined
}
return selected;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>

Get Color Picker value in tags

I'm creating a text editor and so far everything is great, except for a little mess I don't know how to fix.
I need to get the value of the color selected by the user into the tag that is inserted into the textarea.
I don't reeally know how to use JSFiddle, but I think I can share it: https://jsfiddle.net/ElenaMcDowell/mh9rfwct/
<script>//Color picker
//color picker
var theInput = document.getElementById("colorChoice");
var theColor = theInput.value;
theInput.addEventListener("input", function() {
document.getElementById("hex").innerHTML = theInput.value;
}, false);
//Tags
function btnEditor(h, a, i) { // helloacm.com
var g = document.getElementById(h);
g.focus();
if (g.setSelectionRange) {
var c = g.scrollTop;
var e = g.selectionStart;
var f = g.selectionEnd;
g.value = g.value.substring(0, g.selectionStart) + a + g.value.substring(g.selectionStart, g.selectionEnd) + i + g.value.substring(g.selectionEnd, g.value.length);
g.selectionStart = e;
g.selectionEnd = f + a.length + i.length;
g.scrollTop = c;
} else {
if (document.selection && document.selection.createRange) {
g.focus();
var b = document.selection.createRange();
if (b.text != "") {
b.text = a + b.text + i;
} else {
b.text = a + "REPLACE" + i;
}
g.focus();
}
}// helloacm.com
}
</script>
And the HTML
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#VALUEHERE]', '[/color]');">Select</button>
</div>
<textarea id="ECEditor" class="editor-textarea" name="editor-text"></textarea>
function btnEditor() {
var but = document.getElementById('wrapper')
var color = document.getElementById('colorChoice').value
console.log(color)
but.innerHTML = '<button id=\"colorSelect\" onclick=\"btnEditor(\'ECEditor\', \'[color=' + color + ']\',\'[/color]\');">Select</button>'
}
/*
this answer
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#000000]','[/color]');">Select</button>
your request
<button id="colorSelect" onclick="btnEditor('ECEditor','[color=#VALUEHERE]','[/color]');">Select</button>
*/
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<span id = 'wrapper'>
<button id="colorSelect" onclick="btnEditor();">Select</button></span>
</div>
const getCurrentColorPicker = () => {
return document.getElementById("colorChoice").value;
};
function btnEditor(h, a, i) {
console.log(getCurrentColorPicker());
// helloacm.com
var editor = document.getElementById(h);
editor.value = a + getCurrentColorPicker() + i;
// other code...
}

Dynamic button not working when clicked on - Javascript

I am able to create the delete button dynamically, but the action that I have set for it doesn't execute correctly. I am trying to delete one item at a time. I have to only use JavaScript and I can not edit the HTML, but I have provided the code for it, so it can be tested. Any tips would be helpful.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = removeItem;
// remove.setAttribute('onclick', 'removeItem()');
remove.setAttribute('onclick', 'removeItem("' + 'item' + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
ul.remove(item); 
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<title>Household builder</title>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
The problem is the remove function that will remove all the ul elements, should get the related parent of the current clicked element like :
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
Code:
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = removeItem;
// remove.setAttribute('onclick', 'removeItem()');
remove.setAttribute('onclick', 'removeItem("' + 'item' + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age<input type="text" name="age"></label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?<input type="checkbox" name="smoker"></label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
As everyone else has mentioned the element.remove() function removes that element from the DOM not the child as a parameter. You can simply tell the item to remove itself from the DOM with item.remove() in your example or any of the other suggestions where you get the parent element and then do parent.removeChild(item). The benefit of the first method in your case is that you already have item, so there is no need to get the parent where as remove is a shortcut that might not be available in older browsers though.
Second I would not recommend setting your onclick event with setAttribute as that isn't compatible with some older browsers and is kinda hacky.
A more proper way to to this is with the onclick = functionif you only want to add one function the event or the addEventListener("click", function) (attachEvent in very old IE) used in more complicated cases where you need to add multiple events to fire.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function deleteFunction(item) {
return function(event) {removeItem(item)};
}
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = deleteFunction('item' + lastId);
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.remove(); 
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<title>Household builder</title>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
function removeItem(itemid) {
var item = document.getElementById(itemid);
ul.remove(item);
}
This requires an ID, but is called with only an event reference:
remove.onclick = removeItem;
I'd suggest keeping the calling part and editing the removeItem function:
function removeItem(event) {
var item = event.target;
item.parentNode.remove(item);
}
in the removeItem function
function removeItem(itemid) {
var item = document.getElementById(itemid);
ul.remove(item); // HERE
}
change the line to ul.removeChild(item);
BTW
i suggest you to write any code that outside the functions you defined, in
a function that caled after the window as been loaded ..
(you trying access a dom elements that has not been created yet)
document.addEventListener('DOMContentLoaded', function()
// side note - remember to define any variables is a scope according to the range you want them to be known

How to Pass Textbox Value from One Page to another?

I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))

Categories