Form input fails to submit when in a div - forms

I replicated the Developer's example code with success. When i insert a div into the form it fails. How can i submit 'form div input' to a server side function?
* i believe divs and spans are allowed inside forms from here.
* uncommenting the divs causes the div 'output' not to update.
html:
<form id="myForm">
<!--><div>-->
<input name="myEmail" type="text" />
<input type="submit" value="Submit"
onclick="google.script.run.withSuccessHandler(updateEmail)
.processForm(this.parentNode)" />
<!--></div>-->
</form>
<div id="output">
</div>
<script>
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Web App').setSandboxMode(HtmlService
.SandboxMode.NATIVE);
return html;
}
function processForm(formObject) {
var response = "";
response = formObject.myEmail;
return response;
};
Edit:
changed:
<input type="button" value="Submit"
to:
<input type="submit" value="Submit"

I changed the HTML file to this:
<form id="myForm">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"
onclick="processFormJs(this.parentNode)" />
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
And added a console.log('argDivParent: ' + argDivParent); statement. Then in developer tools, show the console. I get this error:
argDivParent: [domado object HTMLDivElement DIV]
Failed due to illegal value in property: 0
this.ParentNode is referring to the DIV and not the FORM. If I take out the DIV, the object returned is:
argDivParent: [domado object HTMLFormElement FORM]
Not:
argDivParent: [domado object HTMLDivElement DIV]
A DIV probably doesn't automatically put INPUT values into it's parent object.
This code does work with a DIV:
<form id="myForm" onsubmit="processFormJs(this)">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"/>
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
For debugging, you can use Logger.log("your text here"); then view the Logs.
function processForm(formObject) {
Logger.log('processForm ran: ' + formObject);
var response = "";
response = formObject.myEmail;
Logger.log('response: ' + response);
return response;
};

Related

using onclick from HTMLservice to run multiple tasks

In the following code, I wanted the button "Add Lines" to:
run the function 'MoreRentals_fromSidebar' from code.gs in the SpreadsheetApp
then "google.script.host.close();" to close the sidebar
When I try to stack the commands, nothing happens. If I try to invoke the submitForm function to run the two commands, nothing happens (although I thought this was working last week and has now stopped).
Any suggestions would be appreciated.
<!DOCTYPE html>
<script>
function getDataFromHtml(idData) {
if (!idData)
idData = "mydata_htmlservice";
var dataEncoded = document.getElementById(idData).innerHTML;
var data = JSON.parse(atob(dataEncoded));
return data;
}
function initialize() {
var data = getDataFromHtml();
// I would have expected to be able to accept the two parameters but whichever is coded second does not get set.
//document.getElementById("myAgency").innerText = data.agency;
//document.getElementById("myRow").innerText = data.row;
// My workaround is to create the header of the sidebar to contain the agency and the line number
var arr = data.first.split("##");
document.getElementById('myTitle').innerText = arr[0]+"\n# line "+arr[1];
//alert(arr[0]+"\n\n"+arr[1]); // used for debugging
}
window.onload = initialize; //Note that there is no "()". It must be this way for this to work!
</script>
<html>
<head>
<base target="_top">
<script>
function submitForm() {
//alert('in submitForm: '+document.getElementById("RentalLinesForm");
google.script.run.MoreRentals_fromSidebar(document.getElementById('RentalLinesForm'));
google.script.host.close();
}
</script>
</head>
<body>
<h1 id="myTitle" ></h1>
<form id="RentalLinesForm">
<label for="numLines">Number of lines to add</label>
<input type="text" id="numLines" name="numLines"><br><br>
<div>
<label for="location">Where to place the new lines:</label><br>
<input type="radio" id="above" name="location" value="above">
<label for="above">Above line</label><br>
<input type="radio" id="below" name="location" value="below">
<label for="below">Below line</label><br>
<input type="radio" id="bottom" name="location" value="bottom">
<label for="bottom">At bottom</label>
<br><br><input type="button" value="Add Lines" onclick="google.script.run.MoreRentals_fromSidebar(document.getElementById('RentalLinesForm'));">
<br><br><input type="button" value="DONE" onclick="google.script.host.close();">
</form>
</body>
</html>

vertx getFormAttribute() returns null

I'm trying to get form data from my html page on a post request but when I use the getFormAttribute() function, it returns null. Here is the code:
Route postArticleRoute = router
.post("/articlePosted")
.handler(routingContext -> {
HttpServerResponse response = routingContext.response();
HttpServerRequest request = routingContext.request();
String title = request.getFormAttribute("title");
String auth = request.getFormAttribute("author");
String body = request.getFormAttribute("body");
System.out.println(title + auth + body);
});
This code returns: 'nullnullnull'
I've double checked that these are the name attributes in the html form. Just in case, here is the html:
<form action="/articlePosted" method="post">
<label>Title of Article</label><br>
<input type="text" name="title" id="postArticle-title"><br><br>
<label>Author</label><br>
<input type="text" name="author" id="postArticle-auth"><br><br>
<label>Image</label><br>
<input type="file" name="file" id="postArticle-img"><br><br>
<label>Body</label><br>
<textarea style="width: 100%; height: 500px;" name="body" id="postArticle-body"></textarea><br><br>
<input type="submit" value="Post">
</form>
Any help would be appreciated.

How to change URL form with GET method?

Form:
<form action="/test" method="GET">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
How to change URL form with GET method?
Before: test?cat3=1&cat3=5&cat3=8&cat3=18
After: test?cat3=1,5,8,18
I want to use jQuery.
Many thanks!
Here you go! This example, using jQuery, will grab your form elements as your question is asking and perform a GET request to the desired URL. You may notice the commas encoded as "%2C" - but those will be automatically decoded for you when you read the data on the server side.
$(document).ready(function(){
$('#myForm').submit(function() {
// Create our form object. You could optionally serialize our whole form here if there are additional parameters in the form you want
var params = {
"cat3":""
};
// Loop through the checked items named cat3 and add to our param string
$(this).children('input[name=cat3]:checked').each(function(i,obj){
if( i > 0 ) params.cat3 += ',';
params.cat3 += $(obj).val();
});
// "submit" our form by going to the properly formed GET url
var url = $(this).attr('action') + '?' + $.param( params );
// Sample alert you can remove
alert( "This form will now GET the URL: " + url );
// Perform the submission
window.location.href = url;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" id="myForm">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
My friend found a solution:
$(document).ready(function() {
// Change Url Form: &cat3=0&cat3=1&cat3=2 -> &cat3=0,1,2
var changeUrlForm = function(catName){
$('form').on('submit', function(){
var myForm = $(this);
var checkbox = myForm.find("input[type=checkbox][name="+ catName +"]");
var catValue = '';
checkbox.each(function(index, element) {
var name = element.name;
var value = element.value;
if (element.checked) {
if (catValue === '') {
catValue += value;
} else {
catValue += '‚' + value;
}
element.disabled = true;
}
});
if (catValue !== '') {
myForm.append('<input type="hidden" name="' + catName + '" value="' + catValue + '" />');
}
});
};
// Press 'Enter' key
$('.search-form .inputbox-search').keypress(function(e) {
if (e.which == 13) {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
}
});
// Click to submit button
$('.search-form .btn-submit').on('click', function() {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
$(".search-form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" class="search-form">
<input name="cat3" value="1" type="checkbox">1
<input name="cat3" value="3" type="checkbox">3
<input name="cat3" value="5" type="checkbox">5
<input name="cat3" value="7" type="checkbox">7
<br />
<input name="cat4" value="2" type="checkbox">2
<input name="cat4" value="4" type="checkbox">4
<input name="cat4" value="6" type="checkbox">6
<br />
<br />
Submit
<br />
<br />
<input type="text" placeholder="Search" class="inputbox-search" />
</form>

view not refreshing after zend redirect

so what i am trying to do, is after the user submit some information, i make a call to a action call saveronda, to save the information on the database, after saving i want to redirect to another page, according to the firebug the html is correct, but the view isnt refreshing.
so here is the code
so in my /rondas/chooseronda ive got this
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
when the user press the button submit i am making an ajax call to /rondas/saveronda and send some data, here is the code:
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
/*
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
*/
//buscar o nome
/*var nomeronda=$("#nomeronda").val();
//buscar a ordem
var ordem=$("#ordem").val();
//tag inicial e tag final
var taginicial=$("#tagini").val();
var tagfinal=$("#tagfim").val();
if(taginicial==tagfinal)
{
alert("a tag inicial não pode ser a mesma que a tag final");
}
else
{
var tags="";
//var allRowsOnCurrentPage = $('#toolbar2').getDataIDs();
var ids = $("#toolbar2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $('#toolbar2').jqGrid ('getRowData', rowId);
tags=tags+rowData.id_tag.toString()+' ';
}*/
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: "sasa"},
datatype: "json"
});
//}
});
});
</script>
in this case i am sending param1 with the value "sasa", and through firebug i am detecting the post to the /rondas/saveronda.
after saving the data i want to redirect the user to /rondas/list, so i have been trying different solution
public function saverondaAction()
{
// action body
/*
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
$param3 = $this->_request->getParam('param3');
$param4 = $this->_request->getParam('param4');
$param5 = $this->_request->getParam('param5');
$rondasModel= new Application_Model_Ronda();
$this->_forward('list', 'rondas');
}
*
*/
$this->_helper->redirector->gotoRoute(
array(
'controller' => 'rondas',
'action' => 'list'
)
);
}
or using redirect or forward..
none have worked, the view is still the /rondas/choosetags and not /rondas/list
what is my error...
thanks in advance..
Your initial view is /rondas/chooseronda when user press submit you make ajax call to /rondas/saveronda and send some data to it. Now if this is successful you want to redirect from the initial page (/rondas/chooseronda) to /rondas/list.
If the redirect code written in action /rondas/saveronda is not working, then you could return a success message back to initial view (/rondas/chooseronda), there you'll need to detect the success message in jQuery ajax code. If successful, put the redirect jQuery code, that will redirect it to /rondas/list.

Multiple forms in one page using jQuery-File-Upload

I am trying to add multiple forms which associates different types of document but when I try to add a file from second form it shows up in primary form submission and also for process event. Please advise what could be wrong here.
<form accept-charset="UTF-8" action="/docs/1" class="documents" enctype="multipart/form-data" id="new_document" method="post">
<div class="input-append" >
<input class="filestyle" did="pdoc" id="document_doc_file" name="document[doc_file]" type="file" uid="template-upload-1" />
</div>
<input id="document_doc_type" name="document[doc_type]" type="hidden" value="1" />
</form><script id="template-upload-1" type="text/x-tmpl">
<div class="upload">
{%=o.name%}<span class="pull-right" id="pbar">Uploading 0%</span></span>
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
</script>
<div id="pdoc"></div>
<form accept-charset="UTF-8" action="/docs/1" class="documents" enctype="multipart/form-data" id="new_document" method="post">
<div class="input-append" >
<input class="filestyle" did="ldoc" id="document_doc_file" name="document[doc_file]" type="file" uid="template-upload-2" />
</div>
<input id="document_doc_type" name="document[doc_type]" type="hidden" value="2" />
</form><script id="template-upload-2" type="text/x-tmpl">
<div class="upload">
{%=o.name%}<span class="pull-right" id="pbar">Uploading 0%</span></span>
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
</script>
<div id="ldoc"></div>
<script type="text/javascript">
$(function () {
$('.documents').fileupload({
dropZone: $(this).find('input:file'),
dataType: 'script',
fileInput: $(this).find('input:file'),
singleFileUploads: true,
add: function(e, data) {
var file, types;
types = /(\.|\/)(pdf|xls|xlsx)$/i;
file = data.files[0];
if (types.test(file.type) || types.test(file.name)) {
uid = $(this).find(':file').attr('uid');
if ($('#' +uid).length > 0) {
data.context = $(tmpl(uid, file).trim());
}
did = $(this).find(':file').attr('did');
$('#' + did).append(data.context);
data.submit();
} else {
alert("" + file.name + " is not a pdf or an excel file.");
}
},
progress: function (e, data) {
if (data.context) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.bar').css('width', progress + '%');
if (progress < 100) {
data.context.find('#pbar').html('Uploading ' + progress + '% ...');
} else {
data.context.find('#pbar').html('Upload Complete');
}
}
}
});
$(document).bind('drop dragover', function (e) {
e.preventDefault();
});
});
</script>
The variable 'this' that you use is ambiguous and might be the cause for the problem.
The simplest solution would be to initiate each form separately - in a for loop over the results of $('.documents') or if you are expecting only two forms just give each of them an id doc1 and doc2 and build the fileupload for each.