taking form input value into a new created div "note" - javascript

I have a school project, where they asked us to create a form where you input values, and when you click submit, a new note will shoe and will be filled with the values from the form.
My problem is that I can't understand how to write the function that creates the notes with the values from the form.
I already did the form and the design for the page. Also started the function to create the note.
This is the form:
<form id="form1">
Mission Details: <textarea name="Details" rows="3" cols="20"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date"> <br> <br>
Mission Due Time: <input type="Text" name="Time"> <br> <br>
<button type="button" onsubmit="createNote()"> Submit </button>
<button type="button" onclick="Clear()"> Clear </button>
</form>
This is the script i started:
function CreateNote(event) {
var form = event.currentTarget;
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
}
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
This is the div for the note and note content:
<div class="note">
<div class="noteDetails">
</div>
</div>
Eventually, the note will have a background from an image in a CSS file, and inside that note, it will have the values from the form.

1. Create a template for your note, lets say you display your text with <p></p>.
2. Leave it with empty values. Give it an id, lets call it "details".
3. After you have the desired values, use document.getElementById("details"), and fill the <p> with the value.
<div class="note">
<div class="noteDetails">
<p id="details"></p>
</div>
</div>
then in your JavaScript you can use
var stringInput = "Some String";
var detailsElement = document.getElementById("details");
detailsElement.innerHTML = " stringInput;

You can now use your div noteDetails. Inside it create three p elements with id details, date and time.
eg:
<div class="noteDetails">
<p id="details"></p>
<p id="date"></p>
<p id="time"></p>
</div>
Change your button element to:
<button type="button" onclick="createNote()"> Submit </button>
Note: your using createNote() in html and using CreateNote in JS
and inside your createNote function just add
function createNote() {
var form = document.getElementById('form1');
var details = form.Details.value;
var date = form.Date.value;
var time = form.Time.value;
var detailsPara = document.querySelector('#details');
detailsPara.innerText = details;
var datePara = document.querySelector('#date');
datePara.innerText = date;
var timePara = document.querySelector('#time');
timePara.innerText = time;
}
remove lines from your code
var form = document.getElementById('form1');
form.onsubmit = CreateNote();
UPDATE: if input values are to be shown immediately then add these to html
Mission Details: <textarea name="Details" rows="3" cols="20" oninput="createNote()"></textarea> <br> <br>
Mission Due Date: <input type="Date" name="Date" oninput="createNote()"> <br> <br>
Mission Due Time: <input type="Text" name="Time" oninput="createNote()"> <br> <br>

Related

Second input box in form doesn't work second time

I have this form:
<form id="addChore" method="post" action="allocate.php">
<label>Name of new chore:</label>
<input type="text" id = "choreName" name="choreName">
<p></p>
<label>Description:</label>
<input type="text" id="description" name="description">
<p></p>
<label>Frequency:</label>
<select id="frequency" name="frequency">
...
</select>
<input type="submit" value="Submit">
</form>
and this jQuery
$(document).ready(function(){
$("#addChore").on('submit',function(e){
e.preventDefault();
$("#error").empty();
var name = $("#choreName").val();
console.log(name);
var description = $("#description").val();
console.log(description);
var frequency = $("#frequency").val();
console.log(frequency);
var message=("Please fill all fields");
// $('#addChore')[0].reset();
if (!name || !description){
$("#error").append("<p>"+message+"</p>");
return false;
}
else{...}
but when I try and use the form a second time, description is empty in the log, while name and frequency accept a new input. I have tried resets and .val("") but nothing seems to change this. Any help? :/
Turns out I had another element with the same id, but defined in php in a separate script

Google Sheets script UserForm - Send Data from Form to Spreadsheet- userform fields not handled correctly

I am new to google scripting. I have followed some tutorials online and created a user form which has 4 input:
company name, qty, agent and comment. The only goal here is to copy data from user form to spread sheet. I have written the following html and functions but data does not get populated after button add is clicked.
I know the addRowData function is working when correct input gets to it. So either I am not population rowData correctly or EventListener does not work correctly. Can anybody please help me find where the issue is?
function addNewRow(rowData) {
const currentDate=new Date();
const ss=SpreadsheetApp.getActiveSpreadsheet();
const ws=ss.getSheetByName("Results");
ws.appendRow([currentDate, rowData.companyName,rowData.qty,rowData.agentName,rowData.commentText]);
return true;
}
<div class="container">
<div>
<div class="form-group">
<label for="company-name">Company</label>
<input type="text" class="form-control" id="company-name">
</div>
<div class="form-group">
<label for="number-boxes">Number of Boxes</label>
<input type="Text" class="form-control" id="number-boxes">
</div>
<div class="form-group">
<label for="agent-name">Agent</label>
<input type="text" class="form-control" id="agent-name">
</div>
<div class="form-group">
<label for="comment-text">Comment</label>
<input type="Text" class="form-control" id="comment-text">
</div>
<button class="btn btn-primary" id="mainButton">Add</button>
</div>
</div>
<script>
function afterButtonClicked(){
var companyName = getElementById("company-name");
var qty = getElementById("number-boxes");
var agentName = getElementById("agent-name");
var commentText = getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked());
</script>
</body>
I would like to propose the following modification.
Modification points:
At document.getElementById("mainButton").addEventListener("click",afterButtonClicked());, the function is run by () of afterButtonClicked() at the load of HTML. In this case, please remove ().
About getElementById("###"), in this case, please add document like document.getElementById("###").
When above points are reflected to your script, it becomes as follows. I think that your Google Apps Script works.
Modified script:
In this case, please modify your Javascript as follows.
<script>
function afterButtonClicked(){
var companyName = document.getElementById("company-name");
var qty = document.getElementById("number-boxes");
var agentName = document.getElementById("agent-name");
var commentText = document.getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = document.getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked);
</script>
References:
EventTarget.addEventListener()
Document.getElementById()

My form is not allowing my result to be displayed on click

I have created a simple Grade calculator and I am just working on little things now. One is not allowing the user to not enter an input into the input box. A possible solution to this is to include the html5 required attribute. To use this I had to put my code into a form going by the W3Schools example here.
HTML required Attribute.
Before implementing this into my code it worked fine and it displayed the result on screen. I just want to know why the form is not allowing my results to display on screen.
My code
var Result;
var Worth;
var caPercentage;
var gradeWanted;
var examPercentage;
var gradeWorth;
var marksNeeded;
//Calculates the Continous Assessment result based on users inputs
function calcCaPercentage() {
//result equals the users Continous Assesment results input value
Result = parseFloat(document.getElementById("caResult").value);
//result equals over Continous Assesment Worth input value
Worth = parseFloat(document.getElementById("caWorth").value);
caPercentage = Worth * (Result / 100);
//CA Percentage result gets displayed here
document.getElementById("caPercentage").innerHTML = caPercentage + "%";
//Returns the Continous Assessment Precentage for the other methods
return caPercentage;
}
//Calcualtes the users exam percentage needed to get the grade they want
function calcExamPercentage() {
//GradeWanted equals the grade the user wants
gradeWanted = parseFloat(document.getElementById("gradeWanted").value);
//x equals the Continous Assessment Precentage from the calcCaPercentage
function calcExamPercentage(){
var x = calcCaPercentage();
examPercentage = gradeWanted - x;
//Exam Percentage gets displayed here
document.getElementById("examPercentage").innerHTML = examPercentage +"%";
//Returns the Exam Precentage for the other methods
return examPercentage;
}
//Calculates the Marks needed for the user to get the grade they want
function calcMarkNeeded() {
//gradeWorth equals what the overall Exam worth input
gradeWorth = parseFloat(document.getElementById("gradeWorth").value);
//y equals the Exam Precentage from the calcExamPercentage function
var y = calcExamPercentage();
//marksNeeded equals a round up version of the overall result
marksNeeded = Math.floor((y / gradeWorth) * 100 /1);
//The marks needed will be displayed here
document.getElementById("marksNeeded").innerHTML = marksNeeded + " Marks!";
}
<form>
<div class="container">
<div class="box boxInput1">
<h4>Calculate your CA Percentage</h4>
<p>Enter your CA Result: <input type="text" class="inputBox" placeholder="Enter you CA Result here.." id="caResult" required></p>
<p>Enter overall CA mark: <input type="text" class="inputBox" placeholder="Enter what the CA is worth here.." id="caWorth" required></p>
<!--
<button type="submit" class="btn" onclick="calcCaPercentage()">
<input type="submit" class="btn" onclick="calcCaPercentage()">
-->
</div>
<div class="box boxResult boxInput1">
<p><br>Your CA percentage is: <br><br><span id="caPercentage"></span></p>
</div>
<div class="box ">
<h4>Calculate the percentage needed to pass the exam!</h4>
<p>Enter the Grade you are aiming to achieve: <input type="text" class="inputBox" placeholder="Enter the Grade you want to get here.." id="gradeWanted" required></p>
<!--
<button type="button" class="btn" onclick="calcExamPercentage()">Calculate</button>
<input type="submit" class="btn" onclick="calcExamPercentage()">
-->
</div>
<div class="box boxResult">
<p><br>Percentage you need to pass the exam is: <br><br><span id="examPercentage"></span></p>
</div>
<div class="box">
<h4>Calculate the marks needed to pass the exam!</h4>
<p>Enter what your exam is worth overall: <br> <input type="text" class="inputBox" placeholder="Enter what the exam is worth here.." id="gradeWorth"></p>
<input type="submit" class="btn" onclick="calcMarkNeeded()" required>
<!-- <button type="button" class="btn" onclick="calcMarkNeeded()">Calculate</button> -->
</div>
<div class="box boxResult">
<p><br>You Need <br><br><span id="marksNeeded"></span></p>
</div>
</div>
</form>
Here is a link to my code working in Codepen
Is this a drawback to using forms ?
Just change <input type="submit" class="btn" onclick="calcMarkNeeded()" required> into <input type="button" class="btn" onclick="calcMarkNeeded()"> or <button class="btn" onclick=calcMarkNeeded()">Calculate</button>.
Submit buttons will submit the form to whatever ( server ) action the form defines.
But there's no server listening for your submit, so your website will just load an empty page instead of the form submit response. And an empty page does not contain the output div you're trying to write the result to.
So never use <input type="submit"> unless you actually want to submit a form.
There's <input type="button"> and even a <button></button> element to use instead.
Also, using the required attribute on a button doesn't do anything. Buttons are to be pressed, not submitted. You can't "force" a user to press the button by using required, like you can "force" a user to fill in a particular input.

Add input to form if button is clilcked

I'm not really sure the best way to go about this but I've laid the framework.
Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.
The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.
What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
Something like this should do the trick:
<!-- modal JS -->
<script type="text/javascript">
var MAX_ITEMS = 10,
added = 0;
function moreItems(){
if (added >= MAX_ITEMS) return;
var newField = document.createElement('input');
newField.type = 'text';
// TODO: Any field setup.
document.getElementById('items').appendChild(newField);
added++;
}
</script>
In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.
some years ago I've wrote an article about making a repeated section using jQuery.
The live example is available on jsFiddle.
In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.
The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).
Try this:
const maxItens = 10,
let itensCount = 0;
function moreItems() {
if (itensCount++ >= maxItens) {
return false;
}
let newInput = document.createElement('input');
// use the iterator to make an unique id and name (to submit multiples)
newInput.id = `Items[${itensCount}]`;
newInput.name = `Items[${itensCount}]`;
document.getElementById('items').appendChild(newInput);
return false;
}
Add type "button" to stop submiting the page (also, your button have two ID):
<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>
The submit button must be inside the form to work:
<form>
<div class="modal-body">
<div id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
</div>
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</div>
<div class="modal-footer">
<button type="submit">Save Items</button>
</div>
</form>
To append itens in sequence the button must be outside of div "itens".

JavaScript code not working when displaying value of html element

I want to display details in div element(id="displayStoragevol2"). Why below code is not working
<hr>
<h3>LocalStorage App Vol-2</h3>
<label>First Name: </label><input type="text" id="firstNamevol2">
<label>Last Name: </label><input type="text" id="lastNamevol2">
<button type="submit" id="fetchDetailsvol2">Submit</button>
<div id="displayStoragevol2"></div>
<hr>
<script>
/*LocalStorage Vol 2*/
document.getElementById('fetchDetailsvol2').addEventListener('click', fetchFunction);
var firstNamevol2 = document.getElementById('firstNamevol2').value;
var lastNamevol2 = document.getElementById('lastNamevol2').value;
var displayStoragevol2 = document.getElementById('displayStoragevol2');
function fetchFunction(){
displayStoragevol2.innerHTML = firstNamevol2 + lastNamevol2;
}
</script>
You read the values from the inputs when the page loads. At that time they are blank.
If you want to read the values when the element is clicked, you need to do so inside the event handler function.
Your script section should be updated as follows,
<script>
document.getElementById('fetchDetailsvol2').addEventListener('click', fetchFunction);
var displayStoragevol2 = document.getElementById('displayStoragevol2');
function fetchFunction(){
var firstNamevol2 = document.getElementById('firstNamevol2').value;
var lastNamevol2 = document.getElementById('lastNamevol2').value;
displayStoragevol2.innerHTML = firstNamevol2 + lastNamevol2;
}
</script>
Since variable firstNamevol2 and lastNamevol2 were in global scope those variables are assigned the values when the page is loaded not when the button is clicked.
You should take care when you are declaring your variables in the process; they should be inside the click event handler.
Below is my working code (with variable and class names tidied).
HTML:
<h3>Input Data</h3>
<label>First Name:</label> <input type="text" id="firstName">
<label>Last Name:</label> <input type="text" id="lastName">
<button type="submit" id="fetchDetails">Fetch Details</button>
<hr>
<h3>Display Data:</h3>
<span id="displayFirstName"></span>
<span id="displayLastName"></span>
<hr>
Javascript:
function fetchData() {
// On click of Fetch Details
document.getElementById("fetchDetails").addEventListener("click", function(event){
event.preventDefault();
// Assign values to variables
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
// Display values in results field
document.getElementById("displayFirstName").innerHTML = firstName;
document.getElementById("displayLastName").innerHTML = lastName;
});
}
fetchData();
Codepen here

Categories

Resources