Storing Variables from a HTML input form? - javascript

I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name"
/></label></p>
<p><label>Age: <input class="text" type="text" id="age" /> c
</label></p>
<p><label>Position: <input class="text" type="text"
id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details"
maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick=""
value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
var employees = [];
and my Javascript
//-------------------------------------------------------------------------
-------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//------------------------------------------------------------------------
-----------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//-------------------------------------------------------------------------
-------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------
------------------------------------
function sortAge(){
}
//-------------------------------------------------------------------------
-------------------------------------
function addRecord(){
}
//-------------------------------------------------------------------------
-------------------------------------
function writeRecords(){
//-------------------------------------------------------------------------
------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------
------------------------------------
function arrayButtons(){
}

You can do something like this.
elements = document.getElementById("myForm").elements;
for (var i = 0; i < elements.length; i++) {
var name = elements[i].name;
var val = elements[i].value;
name = name[0].toUpperCase() + name.slice(1);
var dsply = document.getElementById("dsply");
dsply.innerHTML += "<p>" + name + ": " + val + "</p>";
}
<form id="myForm" name="myForm">
<p>Title of the form</p>
<input type="text" name="user" value="Jon" />
<input type="age" name="age" value="26" />
<input type="text" name="pos" value="CEO" />
<textarea name="details">Enter Details here</textarea>
</form>
<div id="dsply">
</div>

Related

How do I get the value of the added input fields with Jquery?

I am trying to get the values from the added input fields and display it in the textarea.
The values of the input fields will be added once the codeBtn has been clicked and will add it in the textarea. I only have managed to get the values from the first input fields that has been created in HTML.
Moreover, I have tried to add the new value input fields.
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val();
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
But this will give me 'undefined' when I only want to display the values of titleInput1 and contentInput1.
Basically what I'm trying is to get the values from each added input fields to the textarea.
Can anyone please help me? Thank you
Sample HTML Code:
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<label for="">Titel:</label>
<input type="text" id="titleInput1">
<label for="">Content:</label>
<input type="text" id="contentInput1">
</div>
<div class="newInputs">
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
JQuery Code:
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<label for="">Titel:</label>
<input type="text" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" id="contentInput`
const defaultInput_lastpart = `">`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
let titleValue1 = $('#titleInput1').val();
let contentValue1 = $('#contentInput1').val()
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val()
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
Instead using dynamically created id use classes to get inputs value.
Below is the example
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<div class="nwlist"><label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput`
const defaultInput_lastpart = `"></div>`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
totalString = "";
$(".nwlist").each(function(){
totalString = totalString + $(this).find(".titleInput").val() + " " + $(this).find(".contentInput").val() + " ";
})
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<div class="nwlist">
<label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput1">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput1">
</div>
<div class="newInputs">
</div>
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
</body>
</html>
Hope it will help.

Storing "Records" from an input field into in an array with Object Constructor and Javascript?

I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
and here's my Javascript:
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//-----------------------------------------------------------------------------------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//--------------------------------------------------------------------------------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------------------------------------------
function sortAge(){
}
//--------------------------------------------------------------------------------------------------------------
function addRecord(){
}
//--------------------------------------------------------------------------------------------------------------
function writeRecords(){
//--------------------------------------------------------------------------------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------------------------------------------
function arrayButtons(){
}
I understand there's probably a lot of simple mistakes and stuff missing but i'm really having trouble grasping this,
Kind regards

How do I add/remove text boxes with JQuery changing the variable name to keep the name attributes different?

I want to make a book catalog with JQuery to add books to a author. In the code That I have I am trying to add a author and have his books be in a array with his number only. Separated by other authors and their own arrays of books.
For example, when I press the button to add a author a input box appears so that I can add the authors name also a button to add a book that when I press that button I get an input box to add a books name.
When I press the add author again I want to be able to add another author with the same input boxes as before (adding more books to that author).
Also to add multiple books assigned to that author.
I have already done this in the pics but I get an array of everything. I want it to be separated by author.
author1 has an array of {book1, book2, book3...}
author2 has an array of {book13, book14, book15}
(i'm a beginner at JQuery)
This is the code that I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<button class="add_author">Add Author</button>
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author" value="" id="author1" />
<br/>
<button class="add_book">Add book</button>
<div>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function($){
var wrapper = $(".all_fields"); //Fields wrapper
var commonPart = $("#commonPart");
var add_author = $(".add_author"); //Add button ID
var add_subButton = $(".add_book"); //Add sub button ID
$('.my-form .add-box').click(function(){
var n = $('.all_fields').length + 1;
if( 15 < n ) {
alert('Stop it!');
return false;
}
$(add_author).click(function(e){
e.preventDefault();
var htmlToAdd = $('<label for="author' + n + '">Author <span class="author-number">' + n + '</span></label><br/><input type="text" name="author' + n + '" value="" id="author' + n + '" /><br/><button class="add_book">Add book</button><a class="add-book" href="#">Add Book</a><div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$(add_book).click(function(e){
e.preventDefault();
var htmlToAdd = $('<div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
updated code(fixed some bugs..), try this....
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<button onclick="addAuthor()" >Add Author</button><br><br>
<div id="addAuth"></div>
<br><br>
<button onclick="submit()" >Submit</button>
</div>
<div id="result" ></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor(){
authors++;
var str = '<div id="auth'+authors+'"><input type="text" name="author" id="author'+authors+'" />'
+'<button onclick="addMore(\'auth'+authors+'\')" >Add Book</button>'
+'</div>';
$("#addAuth").append(str);
}
var count=0;
function addMore(id){
count++;
var str = '<div id="bookDiv'+count+'">'
+'<input class="'+id+'" type="text" name="book'+id+'" />'
+'<span onclick="addMore(\''+id+'\')" style="font-size: 20px; background-color: green; cursor:pointer;">+</span>'
+'<span onclick="removeDiv(\'bookDiv'+count+'\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">-</span>'
+'</div>';
$("#"+id).append(str);
}
function removeDiv(id){
var val = confirm("Are you sure ..?");
if(val){
$("#"+id).slideUp(function(){$("#"+id).remove();});
}
}
function submit(){
var arr = [];
for(i=1; i<=authors; i++){
var obj = {};
obj.name = $("#author"+i).val();
obj.books = [];
$(".auth"+i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Please try this code and include jquery min js :
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number"></span></label>
<input type="text" name="author" value="" id="author1" />
<br/>
<div>
<label for="author1">book <span class="author-number"></span></label>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
<button type="button" class="add_author" onclick="AddCustomMOre();">Add More</button>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
<script> function AddCustomMOre(){
$(".all_fields ").append('<div id="commonPart" class="commonPart"><label for="author1">Author <span class="author-number"></span></label> <input type="text" name="author" value="" id="author1" /> <br/> <div><label for="author1">book <span class="author-number"></span></label> <input type="text" class="bookName" name="authBook[]"/></div> Remove</div>');
} </script>
You can try this....
<p class="all_fields">
<button class="add_author">Add Author</button>
<div class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author1" value="" id="author1" />
<br/>
<button div-id="1" class="add_book">Add book</button>
<div id="books1">
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<script>
var c=1;
$(".add_author").on("click",function(){
c++;
$(".all_fields").append('<div class="commonPart"><label for="author'+c+'">Author <span class="author-number">'+c+'</span></label><br/><input type="text" name="author'+c+'" value="" id="author'+c+'" /><br/><button class="add_book" div-id="'+c+'">Add book</button><div id="books'+c+'"><input type="text" class="bookName" name="authBook[]"/></div></div>');
});
$(".add_book").on("click",function(){
var id=$(this).attr("div-id");
$("#books"+id).append('<input type="text" class="bookName" name="authBook[]"/>');
});
</script>

HTML5 local storage not storing correctly

I don't know if I have understood the right context of 'storage', but according to some tutorials I used the following Javascript code, to enable a page to locally store (no session) submitted data, but when I close the page and reopen the page, the content do not appear.
script.js
function initiate()
{
var saveButton = document.getElementById('save');
var retrieveButton = document.getElementById('retrieve');
var deleteButton = document.getElementById('delete');
var reviewButton = document.getElementById('review');
saveButton.addEventListener('click', saveItem);
retrieveButton.addEventListener('click', retrieveItem);
deleteButton.addEventListener('click', deleteItem);
reviewButton.addEventListener('click', reviewAll);
}
function saveItem()
{
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage[key] = value;
}
function retrieveItem()
{
var data = document.getElementById('data');
var key = document.getElementById('key').value;
var value = localStorage[key];
data.innerHTML = '<div>' + key + ': ' + value + '</div>';
}
function deleteItem()
{
if (confirm('Delete?'))
{
var key = document.getElementById('key').value;
localStorage.removeItem(key);
data.innerHTML = '<div>Deleted.</div>';
}
}
function reviewAll()
{
for(var i = 0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var value = localStorage[key];
data.innerHTML += '<div>' + key + ': ' + value + '<br></div>';
}
}
addEventListener("load", initiate);
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="mystyles.css" />
<script src="script.js"></script>
<title>Demo HTML5</title>
</head>
<body>
<section id="formSection">
<form name="dataForm">
<label for="key">Key: </label><br />
<input type="text" id="key" name="key" /> <br />
<label for="value">Value: </label><br />
<textarea name="value" id="value"></textarea><br />
<input type="button" id="save" value="Save" />
<input type="button" id="retrieve" value="Retrieve" />
<input type="button" id="delete" value="Delete" />
<input type="button" id="review" value="Review" />
</form>
</section>
<section id="data">
No data
</section>
</body>
</html>
If you are using the browser in privacy mode, it will clear all localStorage data when you close it.

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources