Hi I've done a lot of searching round but can't find anything concrete or that i can get working in my example. Was wondering if anyone could help. I've never used javascript before but have been asked for an assessment to code a piece of software to keep track of a score in a ten pin bowling game. I'm reading up as much as I can but there are a few things I'm still struggling on. I've made a form for the players to input their names and I want to be able to hide the form once they have inputted their names, thus making the interface look less cluttered. Have tried numerous methods but none seem to work for me, I've tried placing the form in a div and using an onClick event to hide the div but it doesn't seem to recognise the div etc, was looking for a few pointers, have taken my failed attempts out of the code to try and give a clear code for you to look at, thank you in advance
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
<style id="jsbin-css">
</style>
<script>
function myFunction()
{
document.getElementById("formy").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<p id="formy"><form>
<h1>Please enter player names!</h1>
<input id="player1" type="text" placeholder="Player 1" />
<input id="player2" type="text" placeholder="Player 2" />
<input id="player3" type="text" placeholder="Player 3" />
<input id="player4" type="text" placeholder="Player 4" />
<input id="player5" type="text" placeholder="Player 5" />
<input id="player6" type="text" placeholder="Player 6" />
<input type="button" value="Save/Show" onclick="insert(),close.this", />
</form></p>
<div id="display"></div>
<script>
var titles = [];
var names = [];
var tickets = [];
var player1Input = document.getElementById("player1");
var player2Input = document.getElementById("player2");
var player3Input = document.getElementById("player3");
var player4Input = document.getElementById("player4");
var player5Input = document.getElementById("player5");
var player6Input = document.getElementById("player6");
var messageBox = document.getElementById("display");
function insert ( ) {
titles.push( player1Input.value );
names.push( player2Input.value );
tickets.push( player3Input.value );
clearAndShow();
}
function clearAndShow () {
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<td>*" + player1Input.value + "<br/><td/>";
messageBox.innerHTML += "*" + player2Input.value + "<br/>";
messageBox.innerHTML += "*" + player3Input.value +"<br/>";
messageBox.innerHTML += "*" + player4Input.value + "<br/>";
messageBox.innerHTML += "*" + player5Input.value + "<br/>";
messageBox.innerHTML += "*" + player6Input.value;
// Clear fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
}
</script>
</body>
</html>
Place an id on the form. Hide the form on the button click. Test it here.
<html>
<form id="b">
<textarea>hey</textarea>
<button onclick="hide(); return false;">click me</button>
</form>
<script>
function hide()
{
document.getElementById('b').style.display='none';
}
</script>
</html>
You can get the element then set style.display='none' to hide it. I put in a return false; to keep the form from posting, and I added the function to a <script> for readability.
In one of your functions, try this to hide everything in the p tag:
document.getElementById("formy").style.display = "none";
Also, I am not sure what you are trying to do on the onclick with 'close.this' - I would personally change it so you just have the function call (if there is an error in your onclick attribute, then the function may not be called):
<input type="button" value="Save/Show" onclick="insert()" />
Related
I'm writing a web app under google sheets and can't get an input field to work. What am I doing wrong?
everything works but uname is always empty (not undefined).
edit: I'm adding the full code after simplifying it as much as I could.
In the log I get "name" regardless of the input I type in.
In the file code.gs:
function doGet () {
var participant = {};
var templ = HtmlService.createTemplateFromFile('out');
return templ.evaluate();;
}
function formSubmit(name) {
Logger.log("name " + name);
}
In out.html
<!DOCTYPE html>
<html>
<head>
<base target ="_top">
</head>
<body dir="rtl"; background-color: #92a8d1;>
<label> Name 1 </label> <input type="text" id="firstname"><br>
<label> Name 2 </label> <input type="text" id="lastname"> <br><br>
<button type="button" id="send">Send</button>
<script>
document.getElementById("send").addEventListener("click", getData());
function getData(){
var uname = document.getElementById("firstname").value;
google.script.run.formSubmit(uname);
}
</script>
</body>
</html>
You want to retrieve the value of <input type="text" id="firstname"> when the button is clicked.
In your current situation, when you see the log with the script editor, only name is retrieved. This is your current issue.
You want to know the reason of the issue.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your script, document.getElementById("send").addEventListener("click", getData()); is used. In this case, when the HTML is loaded, getData() is run by () of getData(). By this, uname becomes "" and "" is sent to formSubmit(uname), then, when you see the log, you see name. And also, in this case, even when the button is clicked, google.script.run.formSubmit(uname); cannot be run. I think that this is the reason of the issue of your script in your question.
In order to avoid this, please modify your script as follows.
Modified script:
From:
document.getElementById("send").addEventListener("click", getData());
To:
document.getElementById("send").addEventListener("click", getData);
By the above modification for your script, when sample is inputted to "Name 1" and click "Send" button, you can see name sample at the log with the script editor.
Reference:
addEventListener()
If I misunderstood your question and this was not the result you want, I apologize.
Here's an example form that you can probably use to accomplish your needs. This form is used as a simple receipt collection system. You can actually take and upload images from a mobile device with it. I also has text and button input types and upload a form node.
Code.gs
var receiptImageFolderId='';
var SSID='';
function onOpen() {
SpreadsheetApp.getUi().createMenu('Receipt Collection')
.addItem('Run as Dialog', 'showAsDialog')
.addItem('Run as Sidebar', 'showAsSidebar')
.addToUi();
var sh=SpreadsheetApp.getActive().getSheetByName("Sheet1");
sh.getRange(sh.getLastRow()+1,1).activate();
}
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Sheet1').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function doGet() {
var output=HtmlService.createHtmlOutputFromFile('receipts').setTitle('thehtml');
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}
function showAsDialog() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Receipts')
}
function showAsSidebar() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showSidebar(ui);
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd")
return {date:datestring};
}
The Html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
Here's what the dialog looks like:
First I'd like to say I read the answers to similar questions including this how to save the content of html form as .html page but that did not solve my problem.
I'm building a reporting system that allows users to use templates to create reports. These templates are html forms and can be developed my any external application or manually. What my application does is, it imports these templates and presents them to the user when he is creating his reports and I want to save the submitted report as as an html file with all the values the user selected, be it text fields or checkboxes.
The above answer suggests using $('#myForm').html(). What this does is get the html of the form but does not include any values entered by the user. How can I achieve this?
Update
I'd like to say this templates are developed by an external application and could have any structure depending on what the user is reporting. So I don't know of any id or name attribute of any of the form inputs used by the creator of the form. The only think I know of is that all the forms are always in a
<div id="reportTemplate"></div>
so that's the only thing I can access with javascript.
Javascript
function CreateHtml(){
var field1 = $("#field1").val();
var field2 = $("#field2").val();
var fieldn = $("#fieldn").val();
var form = $("#myForm").clone();
$(form).find("#field1").val(field1);
$(form).find("#field2").val(field2);
$(form).find("#fieldn").val(fieldn);
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + form);
$('#btn_download').show();
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input placeholder="field1" id="field1" type="text" />
<br/>
<input placeholder="field2" id="field2" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
You can wrap the html content in a variable and export it using anchor tag like below.
function CreateHtml() {
var htmlContent = "";
htmlContent = "<h1>Name - " + $('#name').val() + "</h1><br>" +
"<p>Email - " + $('#email').val() + "</p>";
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + htmlContent);
$('#btn_download').show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input placeholder="Name" id="name" type="text" />
<br/>
<input placeholder="Email" id="email" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
Updated:
function CreateHtml() {
var htmlContent = TraverseThroughReport();
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + htmlContent);
$('#btn_download').show();
}
function TraverseThroughReport() {
var elements = document.getElementById("report").elements;
var htmlContent = "";
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text")
//console.log("it's an empty textfield")
htmlContent = "<h1>" + element.value + "</h1>";
}
//You can add as many conditions for placeholder etc to detect the form element type
return htmlContent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="report">
<input placeholder="Name" id="name" type="text" />
<br/>
<input placeholder="Email" id="email" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
If I had asked my question properly or searched for existing questions using "innerHtml with form values" instead of "how to save html for as files" I would have been taken to this link jquery get all form elements: input, textarea & select with already good answers of which this particular one worked for me
$('input:text, input:hidden, input:password').each(function() {
var v=this.value;
$(this).attr("magicmagic_value",v).removeAttr("value").val(v);
});
$('input:checkbox,input:radio').each(function() {
var v=this.checked;
if(v) $(this).attr("magicmagic_checked","checked");
$(this).removeAttr("checked");
if(v) this.checked=true;
});
$('select option').each(function() {
var v=this.selected;
if(v) $(this).attr("magicmagic_selected","selected");
$(this).removeAttr("selected");
if(v) this.selected=true;
});
$('textarea').each(function() {
$(this).html(this.value);
});
var magic=$('form').html().replace(/magicmagic_/g,"");
$('[magicmagic_value]').removeAttr('magicmagic_value');
$('[magicmagic_checked]').attr("checked","checked").
removeAttr('magicmagic_checked');
$('[magicmagic_selected]').attr("selected","selected").
removeAttr('magicmagic_selected');
alert(magic);
Disclaimer: I am not looking for someone to code this for me just some pointers to help me fix this problem :)
I have the following web page that allows me to add fields dynamically to a form. The current page works. What I want to do is figure out how to make the javascript at the bottom of the page more generic. example I want to pass the templet id and the target id to the function without hard coding the templet id and the target id into the script. Here is the code that I have and works just fine.
I want to make the morefields function so that I can reuse. I want to pass to the function the template and the target. example function moreFields ( templete, target). this way I can use the same function without editing over and over in different web pages. if you look in to the moreFields function you will see that it is hard coded for "readroot" and "writeroot" I want to change the function so it will take parameters and do the same thing it is doing now.
<HTML>
<HEAD>
<META NAME="generator" CONTENT=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org">
<TITLE></TITLE>
<STYLE TYPE="text/css">
div.c1 {display: none}
</STYLE>
</HEAD>
<BODY >
<DIV ID="readroot" CLASS="c1">
Variable Name <INPUT NAME="VarName"><BR>
</DIV>
<FORM METHOD="post" ACTION="/cgi-bin/show_params.cgi">
Function Name: <INPUT NAME="CFunction"> <BR>
Function Alias: <INPUT NAME="AFunction"><BR>
<BR>
<SPAN ID="writeroot"></SPAN>
Function return: <INPUT NAME="AFunction"><BR>
<INPUT TYPE="button" ID="AddMoreFields" VALUE="Give me more fields!" ONCLICK= "moreFields()"> <INPUT TYPE="submit" VALUE="Send form">
</FORM>
<SCRIPT >
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById("readroot").cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById("writeroot");
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields()
</SCRIPT>
</BODY>
</HTML>
I am trying to write the following source code for displaying the manually entered(From Keyboard) text in text boxes using the submit button:
HTML + JavaScript Source:
<html>
<head>
<title>Insert Values</title>
</head>
<body>
<form id="form1">
Title: <input type="text" id="title1" size="25"><br /><br />
Description: <input type="text" id="desc1" size="55"><br /><br />
<input type="button" value="Submit" onclick="doit();">
</form>
<script type="text/javascript">
function doit(){
var title = document.getElementById("title1").value;
var desc = document.getElementById("desc1").value;
document.write("<h3>Title : </h3>" + title + <br />);
document.write("<h3>Description : </h3>" + desc);
}
</script>
</body>
When I use the debugger to trace errors, it gives the message "unfound syntax error" using the browser's debugger. When the webpage is loaded in the browser, it displays the text boxes & the submit button, though after entering text & clicking on the submit button, nothing happens!
Here you are:
function doit() {
var title = document.getElementById("title1").value;
var desc = document.getElementById("desc1").value;
document.write("<h3>Title : </h3>" + title + "< br / >"); // HERE
document.write("<h3>Description : </h3>" + desc);
}
Hope this help.
You just forgot to wrap <br /> by quotes in 15th line:
document.write("<h3>Title : </h3>" + title + "<br />");
also close your html tag
</html>
function doit(){
var myValue=document.getElementById('myTextBox').value;
if(myValue==0){
alert('Pleae Enter Real Value');
}
var myTitle=document.getElementById('title');
myTitle.innerHTML=myValue;
}
<h1 id="title">Title</h1>
<input type="text" id="myTextBox">
<input type="submit" value="Click me!!" onClick="doit()">
I have 2 textBox and 1 button!
I want to insert text to one of these textboxs. When I click to textbox_1 and click button, mytext will appear at textbox_1. When I click to textbox_2 and click button, mytext will appear at textbox_2.
How can I do this by using JavaScript?
Please help me! I'm new on JavaScript!
put id's of the two textboxes as textbox_1 and textbox_2 and put onclick='onCLickButton();' on the <button> tag
and write the following code in the script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies actually I am used to use these functions as I have my own js file having these functions.
please add onfocus='onFocusInput(this);' in the <input> tags and add the following code in the script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
Take a look at the onFocus() attribute for the INPUT tag - and think about keeping track of what was last given the focus. I'm being a little vague as this sounds a lot like homework.
It isn't the prettiest / most delicate solution, but it works and you can build off it to fulfill your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a form such as
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>