I have been tinkering with this problem for most of today and cannot seem to get to a solution with my problem.
I found a script using .gs and html and javascript online which allowed me to upload a file to a google form. At issue though is that I am trying to modify the form to ensure that individuals who upload a file also include their name and email.
I am including my code below.
Essentially, after I call the submit button, I cannot get the code to check the 2 given fields. Can you provide some advice? If I take the 'check' out, the program runs. However, I cannot get the code right to check that the fields are filled out.
Thanks in advance.
/* The script is deployed as a web app and renders the form */
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
// This is important as file upload fail in IFRAME Sandbox mode.
}
/* This function will process the submitted form */
function uploadFiles(form) {
try {
/* Name of the Drive folder where the files should be saved */
var dropbox = form.myName + "Design request form folder" + form.myEmail;
var folder, folders = DriveApp.getFoldersByName(dropbox);
/* Find the folder, create if the folder does not exist */
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
/* Get the file uploaded though the form as a blob */
var blob = form.myFile;
var file = folder.createFile(blob);
/* Set the file description as the name of the uploader */
file.setDescription("Uploaded by " + form.myName);
/* Return the download URL of the file once its on Google Drive */
return "File uploaded successfully " + file.getUrl();
} catch (error) {
/* If there's an error, show the error message */
return error.toString();
}
}
<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<!-- You can also include your own CSS styles -->
<style>
form { margin: 40px auto; }
input { display:inline-block; margin: 20px; }
</style>
<script>
// The function will be called after the form is submitted
function uploadFile() {
var x=document.coForm.fieldName.value;
if (x == null || x ==""){
alert(x);
return false;}
document.getElementById('uploadFile').value = "Uploading File..";
google.script.run
.withSuccessHandler(fileUploaded)
.uploadFiles(document.getElementById("coForm"));
return false;
}
// This function will be called after the Google Script has executed
function fileUploaded(status) {
document.getElementById('coForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<!-- This is the HTML form -->
<form id="coForm" name="coForm">
<!-- Text input fields -->
<input type="text" class="required" id="fieldName" name="myName" placeholder="Your name..">
<input type="email" class="required" id="fieldEmail" name="myEmail" placeholder="Your email..">
<!-- File input filed -->
<input type="file" name="myFile">
<!-- The submit button. It calls the server side function uploadfiles() on click -->
<input type="submit" id="uploadFile" value="Upload File" onsubmit="uploadFile();">
</form>
<!-- Here the results of the form submission will be displayed -->
<div id="output"></div>
Make the "Submit" button a regular button and change the attribute to onmouseup:
<input type="button" id="uploadFile" value="Upload File" onmouseup="uploadFile();">
Remove class="required" from the input fields:
<!-- Text input fields -->
<input type="text" id="fieldName" name="myName" placeholder="Your name..">
<input type="email" id="fieldEmail" name="myEmail" placeholder="Your email..">
Add this code to your uploadFile() function:
function uploadFile() {
var name = document.getElementById('fieldName').value;
var email = document.getElementById('fieldEmail').value;
console.log('name: ' + name);
console.log('email: ' + email);
if (name === "" || email === "") {
alert("Your name and/or email is missing!");
return;
};
Note the console.log() statements. They print information to the browsers console log. To open the browsers log, hit the f12 key, (for Chrome and some others)
Related
I have one form which contain multiple email field so this email to be submitted in database but before that it should validate to avoid duplication, (multiple email fields generated by click on add more button which is present in form ).
I have written ValidateEmail script to avoid duplication however it will work for only one email field but not successfull for multiple email field.
issue:
1) if we type email id in first field it will go for validation and check email exist or not if exist disable submit button if not exist enable button.
2) if we type type email id in second field and after validation it return email not exist then it will enable submit button however in first email field contain duplicate email.
3) if all email fields not contain duplicate values then only enable submit button else it should remain disabled..
<form>
<div>
<input type="email" name="email[]" class="email" onblur="validate_email(this)" /> // initially single filed
// This additional email fields created when click on add more button
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
</div>
<button class="add_more">Add more</button> // this will append extra email fileds
</form>
<script>
// This is the script it will check whether email already exist or not
function ValidateEmail(data) {
var email_id = data.value;
$.ajax({
type: "POST",
url: "<?= base_url('controller') ?>",
data:{
email_id:email_id
},
dataType: 'json',
success: function (response) {
if(response.exist){
// disable submit button and show error
}
else{
//enable submit field and hide error
}
},
error: function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
</script>
If you're using jQuery for this, you can use event delegation for dynamic inserted/removed element. As of now, those will be the email inputs.
Basically the idea here is:
Get the value of last changed/onblur input element.
Validate for existing email on server side (asynchronous check)
Scan through the current available email inputs, then validate and match each value with the Current Email in step (1).
If found, add a error class to the existing email field
Otherwise, add a valid class to the existing email field
You dont need to pass onblur="validate_email(this)" , this can be done in jquery.
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
function isEmail(email) {
// eslint-disable-next-line no-useless-escape
return RegExp(/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i).test(email);
};
function asyncEmailValidate(email) {
return new Promise(function(resolve, reject) {
if (data.includes(email))
return reject('Found duplicated')
return resolve(true);
})
}
$(document).ready(function() {
$(document)
.on('blur',"input.email", function(e) {
// Current email input
var currentEmail = e.target.value,
$emailNode = $(this),
isValid = true;
// Validate email
if (!isEmail(currentEmail))
return;
// Validate email on server side first,
// If found no existing email, then check
// siblings email for duplicates
var serverResult = asyncEmailValidate(currentEmail);
serverResult
.then(function(result) {
// There's no existing email with the inputed email. Now
// look up on other available email inputs fields, except
// the current one, and validate with the current email value
var siblingsEmailInputs = $("input.email").not($emailNode);
if (!siblingsEmailInputs)
return;
if (siblingsEmailInputs.length > 0) {
siblingsEmailInputs.each(function(index) {
console.log('input : ', $(this).val())
if ($(this).val() !== "" && $(this).val() === currentEmail) {
isValid = false;
}
});
}
// Finally update the state for the current field
if (isValid) {
$emailNode.addClass('is-valid');
} else $emailNode.addClass('is-error');
})
.catch(function(error) {
$emailNode.addClass('is-error');
console.log('error:', error);
})
});
})
.email.is-error {
border: 1px solid red;
}
.email.is-valid {
border: 1px solid green;
}
.email {
width: 300px;
margin: 5px;
height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
</pre>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
Those are just the basic way for you to handle email validation and duplicated emails. I think you can take it from here to work on your submit logic.
One quick note, you should leave the ajax submitting process in a separate function, not mixing up with validation process, it will be clearer.
Hope this help
Link working sample: https://codepen.io/DieByMacro/pen/jOOdWMr
Updated:
- I haven't used ajax with jQuery for a while so I'm not sure about the correct syntax, so I've replaced it with a Promised call which works the same as you make an asynchronous request. You can follow the updated version for your reference.
I have an HTML form with text and checkbox inputs, and I want to to download this form data to a text file when I submit the form.
I found a solution to download data from a textbox into a text file, but I don't know how to modify it for the additional text and checkbox inputs that I require.
Here is my current code:
<html>
<head>
<script language="Javascript">
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(Notes));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
function addTextTXT() {
document.addtext.name.value = document.addtext.name.value + ".txt"
}
</script>
</head>
<body>
<form name="addtext" onsubmit="download(this['name'].value, this[’Notes’].value)">
Notes:<input type="text" name=“Note/Users/karlahaiat/Desktop/Copia de checklist.htmls”><br>
Initials:<input type="text" name=“Initials”><br>
<input type="checkbox" name=“check_list[]” value=“Check General Health”>
<b>Check General Health.</b><br>
<input type="checkbox" name=“check_list[]” value=“Check Fluid”>
<b>Check Fluid.</b><br>
<input type="text" name="name" value="" placeholder="File Name">
<input type="submit" onClick="addTexttxt();" value="Save As TXT">
</form>
</body>
</html>
The form above shows the input fields I want in my form however the text file won't download. Any help understanding the syntax would be great!
You code is fairly close to a working solution - consider making the following changes to your code (as shown in the snippet below):
avoid mixing " with the ” character in your HTML markup
ensure valid field names and avoid the name attribute of this form: name=“Note/Users/karlahaia..
consider using addEventListener() to bind event logic to your HTML, rather that using inline onclick, onsubmit, etc, as you currently are
also, consider setting up the form logic after the page has loaded via the DOMContentLoaded event. This ensures that form and input elements that your script depends on are present before your script attempts to access them
/* Run script after DOMContentLoaded event to ensure form element is
present */
document.addEventListener("DOMContentLoaded", function() {
/* Obtain form element via querySelector */
const form = document.querySelector('form[name="addtext"]');
/* Bind listener to forms submit event */
form.addEventListener("submit", function(event) {
/* Prevent browsers default submit and page-reload behavior */
event.preventDefault();
/* Obtain values from each field in form */
const notes = form.querySelector('input[name="notes"]').value;
const initials = form.querySelector('input[name="initials"]').value;
const checkFluid = form.querySelector('input[name="check-fluid"]').checked;
const checkHealth = form.querySelector('input[name="check-health"]').checked;
const filename = form.querySelector('input[name="name"]').value + ".txt";
/* Compose text file content */
const text = `
notes:${notes}
initials:${initials}
check health (checkbox):${checkHealth}
check fluid (checkbox):${checkFluid}
`;
/* Create temporary link element and trigger file download */
const link = document.createElement("a");
const href = "data:text/plain;charset=utf-8," + encodeURIComponent(text);
link.setAttribute("href", href);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
<!-- Ensure that the name attribute does not include invalid characters
or nested "" which cause confusion-->
<form name="addtext">
Notes:<input type="text" name="notes" /><br /> Initials:
<input type="text" name="initials" /><br />
<input type="checkbox" name="check-health" value="Check General Health" />
<b>Check General Health.</b><br />
<input type="checkbox" name="check-fluid" value="Check Fluid" />
<b>Check Fluid.</b><br />
<input type="text" name="name" value="" placeholder="File Name" />
<input type="submit" value="Save As TXT" />
</form>
Hope that helps!
Observations:
Every HTML 5 valid document should have a doctype mentioned at the very beginning, like so: <!DOCTYPE html>
2. Your approach is good, but the click() method on anchors is deprecated in Firefox. So we have to manually dispatch the click event, on the hidden anchor containing the URLEncoded of our TXT file.
Quoted from https://stackoverflow.com/a/1421770/8896148
The click method is intended to be used with INPUT elements of type
button, checkbox, radio, reset or submit. Gecko does not implement the
click method on other elements that might be expected to respond to
mouse–clicks such as links (A elements), nor will it necessarily fire
the click event of other elements.
Non–Gecko DOMs may behave differently.
The function name in onClick="addTexttxt()" was misspeled. It's addTextTXT(). JavaScript is case sensitive!
Instead of directly calling the download(filename, text) function, we should call an intermediary function instead, which will have to collect all the data from your form, and make it into a nice text string. And then, we will pass that string to the download function to make it into a file ready for download.
In onsubmit="someFunctionCall()" we should return false if we don't wish to navigate away from the page (or reload it). So we pas to onsubmit the value returned by someFunctionCall() by adding a return in front of the call: onsubmit="return someFunctionCall()". This way, we can decide inside the someFunctionCall() if we want to navigate away or not by returning true or false.
Text descriptions for checkbox and radio should be placed inside <label for="idOfTheInput">, so the user can click on the text and the checkbox will still activate.
Here is the updated version
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script language="Javascript" >
function download(filename, text){
var pom = document.createElement('a');
pom.style.display = 'none';
document.body.appendChild(pom);
pom.setAttribute('download', filename);
pom.setAttribute('href', 'data:text/plain;charset=utf-8,'
+ encodeURIComponent(text));
pom.click();
document.body.removeChild(pom);
}
//- SIDE NOTE for addTextTXT()
//- This function works as it is, but it's a little sketchy using
//- document.addtext directly inside it. The input we want to check
//- should be passed as a parameter, if in the future we wish to
//- extend this code to work with multiple forms in the same page.
//- It's good for now, though
function addTextTXT(){
//- You may as well do some field validation here, and rename this
//- function validate()
//- Check if the last 4 characters of filename are already ".txt" or ".TXT"
//- or any other variation of lower-case and upper-case
if(document.addtext.filename.value.substr(-4).toLowerCase() != ".txt"){
//- Append ".txt" if missing
document.addtext.filename.value += ".txt"
}
}
//- This function collects all the data present inside the form
//- formats it accordingly, and passes the entyre text content
//- to the download() function above
function downloadData(formElement){
//- We start with an initially empty file content
var text = "";
//- We iterate over all the form's inputs
for(var i=0; i<formElement.length; i++){
var input = formElement[i];
//- We discard the submit button and the filename field.
//- If you remove this if statement the file will contain
//- all the inputs.
if(input.type == "text" && input.name != "filename"){
//- We append to the file content the name of the fiend
//- and it's value in single quotes (i like to quote them
//- to spot empty fields or to easily debug them later)
//- We append after each value an epty line: \n
text += input.name + "='" + input.value + "'\n";
}else if(input.type =="checkbox"){
text += "[" + (input.checked ? "x" : " ") + "] " + input.name + "\n";
}
}
//- Now the text variable contains all the info, so we send it
//- for downloading
download(formElement.filename, text);
//- If we wish, we prevent navigation or page reload by returning false
return false;
}
</script>
</head>
<body>
<form name="addtext" onsubmit="return downloadData(this);">
Notes:<input type="text" name=“Notes” value=""><br>
Initials:<input type="text" name=“Initials” value=""><br>
<input type="checkbox" name="Check General Health"> <b>Check General Health.</b><br>
<input type="checkbox" name="Check Fluid"> <b>Check Fluid.</b><br>
<input type="text" name="filename" placeholder="File Name">
<input type="submit" onClick="addTextTXT();" value="Save As TXT">
</form>
</body>
</html>
Below is a program that I put together, from research and some of my own adding, and I'm having many issues with it. The record_submission function isn't working properly. Every time I test with someone submitting their name, it won't properly record the information which then effects the next function, the notification function which I wrote to automatically send me an email once someone submits a response. Would appreciate some help.
Attached are the images of the Google spreadsheet that I want updated whenever someone submits a response as well as the face of the website people will be submitting information from. The record function is supposed to do that. It's giving me a error saying that the variable isn't properly assigned or something of the sort and the notification email doesn't work properly either.
This is the whole JavaScript code:
//* This function handles the get request from the web browsers */
function doGet(e)
{
//return form.html as the response return
HtmlService.createHtmlOutputFromFile('form.html');
}
// Record all the information entered into the form into a Google Sheet.
function record_submission(form)
{
Logger.log(form);
var ss = SpreadsheetApp.openById("1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8");
var sheet = ss.getSheets()[0]; // Assume first sheet collects responses
// Build a row of data with timestamp + posted response
var row = [ new Date(), // Timestamp
form.last_name[0], // last name
]; // Make sure we are the only people adding rows to the spreadsheet
var lock = LockService.getPublicLock(); // Wait for up to 30 seconds for other processes to finish.
var locked = lock.tryLock(30000);
if (locked)
{
// Save response to spreadsheet
var rowNum = sheet.getLastRow() + 1;
sheet.getRange(rowNum, 1, 1, row.length).setValues([row]);
// Release the lock so that other processes can continue.
lock.releaseLock();
var result = "Response Recorded: \n
"+row.join('\n ');
}
else
{
// Failed to get lock
result =
"System busy, please try again.";
}
// Report result of POST, in plain text
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}
// Send an email to yourself notifying you when someone made a submission.
function notification(last_name, assignment_name)
{
var subject = "New Submission"; MailApp.sendEmail("*my email*#gmail.com",
subject, 'New submission received from ' + last_name + ' for the
assignment: ' + assignment_name );
}
/* This function will process the form when the submit button is
clicked */
function uploadFiles(form)
{
try
{
notification('test','test'); //Retrieve a reference to the folder in Google Drive
var folder_name = "Test_Folder"
var folder =
DriveApp.getFolderById("0By69oDzO6OluTm9KNGVuaUZZdE0");
// Create a new folder if the folder does not exist
if (!folder)
{
folder = folder.createFolder(folder_name);
}
//Get the file uploaded through the form as a blob
var blob = form.myFile;
var file = folder.createFile(blob);
//Set the file description as the name of the uploader
file.setDescription("Uploaded by " + form.LastName);
//Set the file name as the name of the uploader
file.setName(form.LastName + "_" + form.AssignmentName);
//This function should store the information of the submission to a Google Sheet
record_submission(form);
//This function should notify you when there has been a submission
notification(form.LastName, form.AssignmentName);
// Return the download URL of the file once its on Google Drive
return "File uploaded successfully " + file.getUr1();
}
catch(error)
{
// If there's an error, show the error mesage return
error.toString();
}
}
This is the whole HTML code
File Upload
<!--User inputs -->
<h4>First name</h4>
<input type="text" name="FirstName" placeholder = "Type your first name.." >
<h4> Last Name </h4>
<input type="text" name = "LastName" placeholder="Your last name...">
<h4> Assignment Name </h4>
<input type="text" name="Course" placeholder="Course number">
<!--File upload-->
<h4>Upload</h4>
<input type="file" id="file" name="myFile" style="display:block; margin: 20px;" value = "myFile">
<!-- Submit button -->
<input type="submit" value="Submit"
onclick= "this.value='Uploading..';
google.script.run.withsuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form> <div id="output"> </div> <script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
/*check to see if the user's first name input is empty.
If it is empty alert the user to fill in his/her first name */
</script>
<style>
input {display:block; margin: 20px; }
</style>
</body> </html>
I see that your 'input' tags are not wrapped in a 'form' tag, so what gets passed to the 'onclick' function as parameter might actually be the entire <body> tag. Are your inputs nested inside the <form> tag? If not, then this.parentNode would be the entire body of the HTML document.
I put together the quick example illustrating the entire process. On the client side, we are listening for the form submit event. Once the event fires, we call the server-side function via google.script.run and pass the form object to that function as an argument.
Code.gs
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('siderbar'));
}
function logFormObject(form){
Logger.log(form); //check the logs by pressing Ctrl + Return
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // get the 1st sheet in the spreadsheet
sheet.appendRow([form.name, form.lastName, form.age]); //create row contents array from the form object and pass it to the appendRow() method
}
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
Name <br>
<input name="name" /> <br>
Last Name: <br>
<input name="lastName" /> <br>
Age: <br>
<input name="age" /> <br>
<input type="submit" value="send">
</form>
<script>
window.onload = function(){
var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); //prevents redirect to another page
google.script.run.logFormObject(this); // calling the server function in Code.gs
});
}
</script>
</body>
</html>
I have an issue in validating a file in magento form validator,
i have custom validation code for file size like this.
Validation.add('validate-filesize', 'Upload file should be less than 2MB',function(v,elem) {
var file = elem.files;
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}
});
and in my form there are two file filds.
above validation code is working fine for this field.
<input type="file" id="file1" name="file1" value="" class="input-text required-entry validate-filesize">
but it is failing to validate below field
<input type="file" id="file2" name="file2" value="" class="input-text validate-filesize">
The error doesn't lie in the library, but in your validator callback function.
You are checking the size of the file using the following code
var fileSize = file[0].size
But when the user doesn't upload any files, the variable file[0] is undefined. Thus when you do file[0].size, it throws an error saying Cannot read property 'size' of undefined. And that's why further processing of your code stops and you don't get the desired message.
A good way of doing it would be to check if the user has uploaded any files before checking it's size, like so.
var file = elem.files;
if(file.length == 0) return true; // all is good if user didn't upload any file
//go ahead with the rest of the code otherwise
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}
I have a form for editing a ticket that requires a "Reason for Edit". What I would like to do is have that automatically filled in as a result of when any of the input fields or the select dropdown changes. I know this can be done with javascript and an onChange event and have it modify (I believe) the innerHTML of the textarea. I'm strong on PHP/MySQL but javascript is definitely my weakness.
What I do not know and have been unsuccessful searching for, is exactly how to code this. As an example of what I have would be the following code:
<!-- Customers name -->
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" /><br><br>
<!-- Customer Email -->
<input type='text' name='customer_email' onChange="updateReason('Updated Customer Email')" />
If either of those two would be changed then the contents of a textarea would be updated and end with a carriage return.
Any help (or even pushed in the right direction / links to a guide) is appreciated.
HTML:
<form name="frmTest" action="test.html">
<textarea name="reason"></textarea>
<!-- Customers name -->
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" />
<!-- Customer Email -->
<input type='text' name='customer_email' onChange="updateReason('Updated Customer Email')" />
</form>
native HTML implementation:
function updateReason(text) {
document.frmTest.reason.value += text + '\r\n';
}
My implementation separates the business logic from the design. It also uses more advanced features of JavaScript (which are supported by practically every browser).
http://jsfiddle.net/xrZk2/1/
For the lazy, create a textarea like so:
<input type="text" name="customer_name" id="customer_name" /><br /><br />
<input type="text" name="customer_email" id="customer_email" /><br /><br />
<textarea name="customer_change_log" id="customer_change_log" readonly="readonly"></textarea>
And use the following JavaScript.
(function () {
'use strict';
var updateReason = function (reason) {
document.getElementById('customer_change_log').innerHTML += reason + '\n';
};
document.getElementById('customer_name').onchange = function () {
updateReason('Updated Customer Name');
};
document.getElementById('customer_email').onchange = function () {
updateReason('Updated Customer Email');
};
}());
And a little CSS never hurt anyone.
#customer_change_log {
height: 5em;
resize: vertical;
width: 15em;
}
A somewhat different approach:
HTML:
<p><label>Customer Name: <input type='text' name='customer_name'/></label></p>
<p><label>Customer Email: <input type='text' name='customer_email'/></label></p>
<p><label>Edit Reason: <textarea id="edit_reason" rows="6" cols="60"></textarea></label></p>
JS:
(function() {
var reasons = {
'customer_name': 'Updated Customer Name',
'customer_email': 'Updated Customer Email'
};
var inputs = document.getElementsByTagName("INPUT"), len, i, input;
var editReason = document.getElementById("edit_reason"), reasonText;
for (i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
input.onchange = (function(name) {
return function() {
reasonText = editReason.value || "";
if (reasons[name]) {
if (reasonText.indexOf(reasons[name]) < 0) {
editReason.value = reasonText + '\n' + reasons[name];
editReason.value = editReason.value.replace(/^\n+/, '');
}
}
};
}(input.name));
};
}());
You can see it in this fiddle. The biggest difference is in the separation of the logic from the markup, using this:
var reasons = {
'customer_name': 'Updated Customer Name',
'customer_email': 'Updated Customer Email'
};
The input tag that needs to be updated give it id or a class, each tag has unique id so its better to give it id like this
<input type='text' id="id-name" />
You need to add jQuery file and attach jQuery file with your html page. Attachment is written in head tag and is shown as follows.
<head>
<script src="jquery.min.js"></script>
</head>
On the following input tag wen values is changes the function updateReason is called. Code in the script tag is written in the same html file and if you want to separate your JavaScript or jQuery code from html you can write that in .js file without the script tag and just attach that file in your html page.
<input type='text' name='customer_name' onChange="updateReason('Updated Customer Name')" />
<script>
function updateReason(text)
{
// # is used for id and . is used for referring class in jQuery
$('#id-name').val(text);
}
</script>