javascript Converting function to a generic form - javascript

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>

Related

How can I collect data from multiple HTML checkboxes and input that data into a google sheet?

I am continuing work on a previous project: Google Sheet Data in a Sidebar
Now, I would like to retrieve the items that have been checked in the sidebar and return that data to the Code.gs file and ultimately the Google Sheet (see code below). Can you offer suggestions on how to do this?
Below, I am trying to add the checked items to the "students" array. I would then like the "Submit Early Release" button to send the "students" array to the Code.gs file. However, I am unsure how to push the checked items to the array properly.
Page.html
> <!DOCTYPE html>
><html>
> <head>
> <base target="_top">
> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
> </head>
> <body>
> <script>
> function addStudents(studentList){
> $('#rangeResult').text(studentList);
>
> document.write(new Date().toLocaleDateString());
>
> var students = [];
> for (var i = 0; i < studentList.length; i++) {
> document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);
> }
> document.write('<br><input type="button" value="Submit Early Release" onclick="google.script.host.close()" />');
> document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
> };
>
> google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
> </script>
> </body>
></html>
Thank you for your help!
Update
Madhav, thank you for your suggestions. I've adapted your code to fit my scenario, but I'm still having trouble getting the array data back to the spreadsheet. Specifically, when I click the "Submit Early Release" button the sidebar closes but no data is written into the specified cell. Would you mind taking a look?
Page.html
Added another "src=" line for jquery - not sure if this is needed???
Added "collectNames" function to get checked names and send them back
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
function addStudents(studentList){
$('#rangeResult').text(studentList);
document.write(new Date().toLocaleDateString());
//var students = [];
for (var i = 0; i < studentList.length; i++) {
document.write('<br><input type="checkbox" class="special" name='+ studentList[i]+ 'id="i" value="i">'+ studentList[i]);
}
document.write('<br><input type="button" value="Submit Early Release" onclick="collectNames()" />');
document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
};
function collectNames(){
var students = [];
var checkboxes=document.getElementsByClassName("special"); //get all checkboxes
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked){
students.push(checkboxes[i].getAttribute("name")); //if checked then push to array the value
}
}
//now send the finalarray to the destination
google.script.run.releasedStudents(students);
google.script.host.close();
};
google.script.run.withSuccessHandler(addStudents).earlyReleaseList();
</script>
</body>
</html>
Code.gs
function releasedStudents(values) {
var doc = SpreadsheetApp.openById("1OF6Y1CTU9dkIgd1P-nw-5f2lqHSS5cGZytndwzJhw-o");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange('V20').getValue();
cell.setValue(values);
}
If you want to push checked items into the array, then the first thing you will need to ensure is that each checkbox carries the value it represents in some form or the other. Your code does attempt to do that but when you write
document.write('<br><input type="checkbox" name="studentList[i]" id="i" value="i">'+ studentList[i]);
the name attribute of each checkbox is always the same because it is a constant string ("studentList[i]") and not the value from the array, so it should be replaced with :
document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]);
Once we are done with the input , we should be able to collect values from the checked boxes only ..one way to do that is to assign a class to all the checkboxes so that they can later be accessed via getElementsByClassName() function.
Once obtained, the value attribute of only those checkboxes should be pushed to the array which have the checked property as true.
A slightly different code demonstrating this is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="clickthis">Click this</button>
</body>
<script>
var studentList=["nevil","ron","draco","harry"];
var finalarray=[];
function runmyfun(){
var checkboxes=document.getElementsByClassName("special"); //get all checkboxes
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked){
finalarray.push(checkboxes[i].getAttribute("name")); //if checked then push to array the value
}
}
//now send the finalarray to the destination
}
document.getElementById("clickthis").onclick=function(){
document.write(new Date().toLocaleDateString());
for (var i = 0; i < studentList.length; i++) {
document.write('<br><input type="checkbox" class="special"name='+studentList[i]+ ' id="i" value="i">'+ studentList[i]); //concat properly
}
document.write('<br><input type="button" value="Submit Early Release" onclick="runmyfun()" />');
document.write('<input type="button" value="Close" onclick="google.script.host.close()" />');
};
</script>
</html>
I hope this is what you were looking for and not something else.

Hiding the form once data saved in javascript

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()" />

Execute stringByEvaluatingJavaScriptFromString before click event

I am using UIWebView in iPhone and loaded one HTML page from resources.
Following is my HTML page code:
<html>
<head>
<title></title>
<SCRIPT language="JavaScript">
function callme(id)
{
var input = 'input'+id;
document.getElementById(input).value = document.getElementById('code').value;
}
</SCRIPT>
</head>
<body>
<input type=hidden id='code' name='code'>
<a href="#" id="click1" name="click1" onclick='callme(1);'>Click1</a>
<input type="text" id="input1" name="input1">
</br>
<a href="#" id="click2" name="click2" onclick='callme(2);'>Click2</a>
<input type=text id="input2" name="input2">
</br>
<a href="#" id="click3" name="click3" onclick='callme(3);'>Click3</a>
<input type=text id=input3 name=input3>
</body>
</html>
I have inject some Javascript on page using following code:
[webView stringByEvaluatingJavaScriptFromString:#"var field1 = document.getElementById('code'); field1.value='Code010203';"];
What I want is when user click on link first injected script should run and then onclick event's function(callme(1) or 2 or 3) for link(Click1,Click2 or Click3) should execute.
function callme(id)
{
injectedCode();
var input = 'input'+id;
document.getElementById(input).value = document.getElementById('code').value;
}
where injected code is:
[webView stringByEvaluatingJavaScriptFromString:#"var field1; function injectedCode() {field1 = document.getElementById('code'); field1.value='Code010203';}"];
I'm not 100% sure I understand your question.
If you want the click event to run the injected code, would this approach work for you :
(this is the injected code below)
document.querySelector("#click1").onclick = function() {
// do your new stuff here
clickMe(1);
};
You could make this generic with a bit of effort e.g.
document.querySelector("a[id^=click]").onclick = function() {
// do your new stuff here
var clickMeArg = this.id.substring("click".length);
clickMe(parseInt(clickMeArg, 10));
};

Getting rid of Value attribute of a textBox when using clone method in jQuery

I'm having a problem with this form I'm working on. Whenever I add, or refresh the page, the values are still there. I believe this is because the clone method copies the value attribute from the textBox. Is there any way I can get rid of them when I add another textBox?
<html>
<head>
<title>JQuery Example</title>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
function removeTextBox()
{
var childCount = $('p').size() //keep track of paragraph childnodes
//this is because there should always be 2 p be tags the user shouldn't remove the first one
if(childCount != 2)
{
var $textBox = $('#textBox')
$textBox.detach()
}
}
function addTextBox()
{
var $textBox = $('#textBox')
var $clonedTextBox = $textBox.clone()
//document.getElementById('textBox').setAttribute('value', "")
$textBox.after($clonedTextBox)
}
</script>
</head>
<body>
<form id =
method="POST"
action="http://cs.harding.edu/gfoust/cgi-bin/show">
<p id= "textBox">
Email:
<input type = "text" name="email" />
<input type ="button" value ="X" onclick = "removeTextBox()"/>
</p>
<p>
Add another email
</p>
<input type="submit" value="submit"/>
</form>
</body>
</html>
The Following addition should work:
var $clonedTextBox = $textBox.clone();
$($clonedTextBox).val('');

Disable the text boxes

I am beginner to html. I have two text boxes say t1 and t2 If t1 is filled with some data then then other text box t2 should be disable. Please let me know hot to do it. Thanks in advance
Based on your simple scenario description, here's an implementation that works cross-browser and without any third-party javascript library:
<html>
<head>
<script type="text/javascript">
window.onload = function(){
var t1 = document.getElementById("t1");
var t2 = document.getElementById("t2");
t1.onchange = function(){
t2.disabled = t1.value.length > 0;
}
}
</script>
</head>
<body>
<form>
t1:<input type="text" id="t1" name="t1" /><br/>
t2:<input type="text" id="t2" name="t2" />
</form>
</body>
</html>
<head>
<script type="text/javascript">
function verify(){
var t1 = document.getElementById ('first');
var t2 = document.getElementById ('second');
if (t1.value != '') {
t2.setAttribute('disabled','disabled');
return true;
}
if (t2.value != '') {
t1.setAttribute('disabled','disabled');
return true;
}
}
</script>
</head>
<body>
...
<input type="text" id="first" onblur="verify()">
<input type="text" id="second" onblur="verify()">
...
</body>
You can't achieve this with plain HTML.
Following the guidelines of progressive enhancement, you should first implement a server side check in whatever form handler you are using to process the submitted data.
Then you can consider adding JavaScript for a client side check. Something along the lines of:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Disabling form controls</title>
</head>
<body>
<form id="myForm" action="http://example.com/">
<div>
<input name="t1">
<input name="t2">
</div>
</form>
<script type="text/javascript">
(function () {
var t1 = document.forms.myForm.elements.t1;
var t2 = document.forms.myForm.elements.t2;
var handler = function handler() {
t2.disabled = (t1.value !== "");
};
t1.onchange = handler;
}());
</script>
</body>
</html>
(Although I would use a library such as YUI or jQuery to add event handlers in a fashion that is better protected from overwriting in a crossbrowser compatible way).
You might want some tutorials on JavaScript and the DOM so that this makes sense.

Categories