Get text from textarea - textbox

I feel like I am going insane trying to get the most simple of things to work! I have a mailing list in Google Spreadsheet on Google Drive. I have created a user interface that prompts for the message that the user wants to include in the email. My code looks like this.
function startBulkEmailUI(e) {
//create main form
var app = UiApp.createApplication().setTitle('Send Email').setWidth(602).setHeight(402);
var scrollPanel = app.createScrollPanel().setId('scrollPanel').setAlwaysShowScrollBars(true) ;
var mainPanel = app.createVerticalPanel().setId('mainPanel');
mainPanel.setStyleAttribute('border', '1px solid #C0C0C0').setWidth("100%").setHeight("100%");
scrollPanel.add(mainPanel);
//create panel for input boxes etc
var inputPanel = app.createVerticalPanel().setId('inputPanel').setWidth("100%").setHeight("100%").setSpacing(0);
var messageLabel = app.createLabel('E-mail Message');
var messageBox = app.createTextArea().setName('messageBox').setId('messageBox').setVisible(true).setWidth(400).setHeight(150);
var attachmentLabel = app.createLabel('E-mail Attachment');
var attachmentCheckBox = app.createCheckBox('Attach a file').setValue(false);
inputPanel.add(messageLabel).add(messageBox).add(attachmentLabel).add(attachmentCheckBox);
mainPanel.add(inputPanel).setCellHorizontalAlignment(inputPanel, UiApp.HorizontalAlignment.CENTER) ;
inputPanel.setCellHorizontalAlignment(messageLabel, UiApp.HorizontalAlignment.CENTER);
inputPanel.setCellHorizontalAlignment(messageBox, UiApp.HorizontalAlignment.CENTER);
inputPanel.setCellHorizontalAlignment(attachmentLabel, UiApp.HorizontalAlignment.CENTER);
inputPanel.setCellHorizontalAlignment(attachmentCheckBox, UiApp.HorizontalAlignment.CENTER);
//add function buttons
var buttonsPanel = app.createHorizontalPanel().setStyleAttribute('margin', '20px').setWidth(500);
var closeButton = app.createButton('Close',app.createServerHandler('close_'));
var sendButton = app.createButton('Send!').setId("sendButton");
buttonsPanel.setId('buttonsPanel').add(closeButton).add(sendButton);
mainPanel.add(buttonsPanel).setCellHorizontalAlignment(buttonsPanel, UiApp.HorizontalAlignment.CENTER);
buttonsPanel.setCellHorizontalAlignment(closeButton, UiApp.HorizontalAlignment.CENTER).setCellHorizontalAlignment(sendButton, UiApp.HorizontalAlignment.CENTER);
app.add(scrollPanel);
//handlers
var handlerSendEmails = app.createServerClickHandler('sendEmails');
handlerSendEmails.addCallbackElement(inputPanel);
sendButton.addClickHandler(handlerSendEmails);
//show the form
ss.show(app);
return app;
}
function sendEmails(e) {
var contactDetail = getContactDetail();
var count = 0;
var failed = 0;
for (i in contactDetail) {
var row = contactDetail[i];
var emailAddress = row[9];
var stuff = e.parameter.messageBox.value;
Logger.log(e.parameter);
var message = 'Hi, ' + row[4] + '\n\n' + 'This is a test!'; // Second column
var subject = 'Test Email';
try {
// MailApp.sendEmail(emailAddress, subject, message);
count = count+1;
} catch(e) {
failed = failed+1;
}
}
var msg = stuff;
Browser.msgBox('Debug Msg', msg, Browser.Buttons.OK);
}
I want the user to enter information into the textarea, which I can then use as the body of an email. I discovered there is no getText, so I have found hundreds of answer saying it should look like the code above: you create a callbackhandler, then use e.parameter.OBJECT_NAME.value to get the text. It simply does not work for me and I have tried every workaround that I can think of. Any suggestions? Is my code faulty (I know it's messy...)?

The "normal" way to get a widget's value in a handler function is in the form e.parameter.widgetName so in you case you should simply use
var stuff = e.parameter.messageBox; without the ".value" , the result is a string.

Related

IOS automation script error

What wrong with this automation script.I have only one textfield where user enters his email id.Everytime i run this,i keep getting "Wrong number of text fields".
var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
target.logElementTree();
//var textfieldscount = UIATarget.localTarget().frontMostApp().mainWindow().textFields()["UserText"];
var textfieldscount = UIATarget.localTarget().frontMostApp().mainWindow().textFields()[0];
var count = textfieldscount.length;
//var count = view.textFields();
if(count!=1){
UIALogger.logFail("Wrong number of text fields");
}else{
UIALogger.logFail("Right number of text fields");
}
In case of a single Test field on your app window it's better to handle it using the code below (if you simply want to check whether it's visible and has got a correct name):
var txt_field_name = textfieldscount .name();
if (textfieldscount .isVisible () && txt_field_name .match("UserText")){
UIALogger.logPass("Txt field is on a screen");
... YOUR_CODE_HERE...
} else {
UIALogger.logFail("Wrong number of text fields");
}

How do you get the selected listBox item as a String?

I have been trying to build a small app that takes the selected item from a listBox and appends it to the filename of a file that will be uploaded. I can display everything correctly, and the file gets uploaded, but the value that should be appended to the filename is 'undefined'. Here is a sample:
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
var panel = app.createVerticalPanel();
var listBox = app.createListBox().setName('myList').setId('myList').setWidth('80px');
listBox.addItem('Value1');
listBox.addItem('Value2');
listBox.addItem('Value3');
listBox.addItem('Value4');
panel.add(listBox);
app.add(panel);
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('Submit'));
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
var fileBlob = e.parameter.thefile;
var app = UiApp.getActiveApplication();
var doc = DocsList.createFile(fileBlob).rename(e.parameter.myList+Utilities.formatDate(new Date(), "GMT", "MM-dd-yy"));
return app;
}
How can I get the name of the file to take the value from the listBox?
You added the listBox to the app instead of adding it to the formpanel content.
This has 2 consequences :
1 - the list stays visible after submitting
2 - the list is not received by the doPost since it is not in the form...
Try it like this :
function doGet() {
var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
var panel = app.createVerticalPanel();
var listBox = app.createListBox().setName('myList').setId('myList').setWidth('80px');
listBox.addItem('Value1');
listBox.addItem('Value2');
listBox.addItem('Value3');
listBox.addItem('Value4');
panel.add(listBox);
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('Submit'));
formContent.add(panel);
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
var fileBlob = e.parameter.thefile;
var doc = DocsList.createFile(fileBlob).rename(e.parameter.myList+' '+Utilities.formatDate(new Date(), "GMT", "MM-dd-yy"));
var app = UiApp.getActiveApplication();
return app;
}

Can't access to event posted values

i'm writing a little google apps script which allow to select several names among a list of developpers. But in my doPost(e) method, i can't access to the array of posted values (it's undefinded), event if i check all the checkboxes...
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// add the new menu
var menuEntries = [];
menuEntries.push({name: "Edit page", functionName: "start"})
ss.addMenu("My tools", menuEntries);
}
function start() {
var app = UiApp.createApplication();
app.setTitle("Edit page");
var formPanel = app.createFormPanel();
var mainPanel = app.createVerticalPanel();
var gridPanel = app.createGrid(1, 2);
// developpers
var developperPanel = app.createVerticalPanel()
var developpers = [];
developpers.push( "John", "Peter", "Max", "Johnny" );
for (var i = 1; i < developpers.length; ++i) {
var checkbox = app.createCheckBox(developpers[i]).setName("dev"+i);
developperPanel.add(checkbox);
}
gridPanel.setWidget(0,0,app.createLabel("Developpers : "));
gridPanel.setWidget(0,1,developperPanel);
// submit button
mainPanel.add(gridPanel);
mainPanel.add(app.createSubmitButton().setText("OK"));
formPanel.add(mainPanel);
app.add(formPanel);
var ss = SpreadsheetApp.getActive();
ss.show(app);
}
function doPost(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(e.values[0])); // Here is the error.
return app;
}
In the exemple, the list is fixed but in my real script, i create the list thanks to the Spreadsheet.
Thanks
Max
The correct way to see the checkboxes values is using e.parameter[name], like you said yourself on a comment. Here is some code example:
function start() {
//...
var developpers = ["John", "Peter", "Max", "Johnny"];
//you were skiping the first developer
for (var i = 0; i < developpers.length; ++i) { //array starts on zero, not one
var checkbox = app.createCheckBox(developpers[i]).setName("dev"+i);
developperPanel.add(checkbox);
}
//...
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var developpers = ["John", "Peter", "Max", "Johnny"]; //repeat it here or make it global, if it's static like this
var checked = [];
for( var i in developpers )
if( e.parameter['dev'+i] == 'true' )
checked.push(developpers[i]);
app.add(app.createLabel(checked));
return app;
}
You should use e.parameter.yourCheckBoxName
for example:
function doPost(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(e.parameter.dev1); // Access checkbox by its name
return app;
}
This would show status of check box "Peter", when it is checked. You can modify based on your need.

unable to set and get values in localstorage

I'm developing a web application in iPhone using Phonegap. In this app, I want to send data from one page to another within the same index.html file. I'm using local storage to send data, but I am unable to send values. whenever the local storage statements are encountered, it skips the remaining statements also in that javascript function. Please tell me the solution. Do I need to add any plugin to use local storage?
{
var name = document.getElementById("usernameTextField").value; //TextField of page1
var fullname = document.getElementById("nameLabel").innerHTML; //label of page1
localstorage.setItem("userName", name);
localstorage.setItem("fullname1", fullname);
var getusername = localstorage.getItem("userName");
var getname = localstorage.getItem("fullname1");
fullnameLabel.innerHTML = getname.value; //label of page2
userNameLabel.innerHTML = getusername.value; //label of page2
}
Try with this
{
var name = document.getElementById("usernameTextField").value; //TextField
var fullname = document.getElementById("nameLabel").innerHTML; //label
localStorage.setItem("userName", name);
localStorage.setItem("fullname1", fullname);
var getusername = localStorage.getItem("userName");
var getname = localStorage.getItem("fullname1");
alert(getname + " " + getusername); //label
}
Please check the full code here

An observer for page loads in a custom xul:browser

In my firefox extension I'm creating a xul:browser element. I want to have an observer that intercepts any url changes within the embedded browser and opens the url in a new browser tab (in the main browser). I'd also like new windows spawned by the xul:browser window to open in a tab instead of a new browser window.
I've created an observer which works, but I don't yet know how to apply that observer only to the xul:browser element.
function myFunction(){
var container = jQuery("#container")[0];
var new_browser_element = document.createElement('browser');
container.appendChild(new_browser_element);
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(myObserver, "http-on-modify-request", false);
}
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic != 'http-on-modify-request'){
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
// alert(aSubject.URI.spec);
// Now open url in new tab
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
}
};
You could try:
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic == 'http-on-modify-request')
{
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var url = aSubject.URI.spec;
var postData ;
if (aSubject.requestMethod.toLowerCase() == "post")
{
var postText = this.readPostTextFromRequest(request);
if (postText)
{
var dataString = parseQuery(postText);
postData = postDataFromString(dataString);
}
}
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow);
//check if it is one of your mini browser windows
if (jQuery(DOMWindow).hasClass('mini_browser'))
{
openInTab(url, postData);
var request = aSubject.QueryInterface(Components.interfaces.nsIRequest);
request.cancel(Components.results.NS_BINDING_ABORTED);
}
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
readPostTextFromRequest : function(request) {
var is = request.QueryInterface(Components.interfaces.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Components.interfaces.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
// Seek locks the file so, seek to the beginning only if necko hasn't read it yet,
// since necko doesn't seek to 0 before reading (at lest not till 459384 is fixed).
if (ss && prevOffset == 0)
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
dump("Failed to Query Interface for upload stream.\n");
}
}
return null;
},
readFromStream : function(stream, charset, noClose)
{
var sis = Components.classes["#mozilla.org/binaryinputstream;1"]
.getService(Components.interfaces.nsIBinaryInputStream);
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
};
function openInTab(url, postData)
{
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow)
{
// Use an existing browser window, open tab and "select" it
recentWindow.gBrowser.selectedTab = recentWindow.gBrowser.addTab(url, null, null, postData);
}
}
function parseQuery() {
var qry = this;
var rex = /[?&]?([^=]+)(?:=([^&#]*))?/g;
var qmatch, key;
var paramValues = {};
// parse querystring storing key/values in the ParamValues associative array
while (qmatch = rex.exec(qry)) {
key = decodeURIComponent(qmatch[1]);// get decoded key
val = decodeURIComponent(qmatch[2]);// get decoded value
paramValues[key] = val;
}
return paramValues;
}
function postDataFromString(dataString)
{
// POST method requests must wrap the encoded text in a MIME
// stream
var stringStream = Components.classes["#mozilla.org/io/string-input-stream;1"]
.createInstance(Components.interfaces.nsIStringInputStream);
if ("data" in stringStream) // Gecko 1.9 or newer
stringStream.data = dataString;
else // 1.8 or older
stringStream.setData(dataString, dataString.length);
var postData = Components.classes["#mozilla.org/network/mime-input-stream;1"].
createInstance(Components.interfaces.nsIMIMEInputStream);
postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);
return postData;
}
I'll update this to fill in the blanks in a bit.
edit: see http://forums.mozillazine.org/viewtopic.php?p=2772951#p2772951 for how to get the source window of a request.
Request cancellation code from http://zenit.senecac.on.ca/wiki/index.php/Support_For_OpenID.
see http://mxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIRequest.idl for details on nsIRequest.
See http://forums.mozillazine.org/viewtopic.php?p=2404533#p2404533 and https://developer.mozilla.org/en/XUL/Method/addTab for the definition of addTab.
parseQuery comes from http://blog.strictly-software.com/2008/10/using-javascript-to-parse-querystring.html.
See https://developer.mozilla.org/en/Code_snippets/Post_data_to_window#Preprocessing_POST_data for how to process post data in a form suitable for addTab.
ReadPostFromText and ReadTextFromStream both come from firebug (though slightly modified)

Resources