javascript update controls onload - javascript

iv'e got 2 html pages
one performs a "get" method on the other
these pages are duplicates in that they own they both poses a form with the same control types
and control names
when i submit my form from the source page my url string consist of the values appended together after a '?' char
....?txtName=era&txtAge=28&gender=male&langHe=on&langEn=on&select=1
in the detestation page onload i call a function which splits the control names and their values and sets them
// this is called from <body onload="f();">
function f() {
var st = new String(location.search);
st = st.substring(1, st.length);
var input = st.split('&');
var value;
var ctrl;
var val;
var _control;
for (var i = 0; i < input.length; i++)
{
value = input[i].substring(0, input[i].length);
ctrl = value.substring(0, value.indexOf('='));
val = value.substring(value.indexOf('=') + 1, value.length);
_control = document.getElementsByName(ctrl);
_control.value = val;
}
}
i debugged this function and checked that every thing is put in to place as it should
the problem is that after the value are set to the controls
they do not appear on the page , as if they didn't get set at all
additionally in Google chrome i get a "Aw,Snap!" Error after these actions (Aw Snap happens only when i debug )
i'm new to java-script and i'm guessing there's a problem with the way i'm assigning these values , i tried also just the first control which is a text type input and it also does not get updated .
any idea's on why this doesn't work ?
thanks in advance
eran.

Try changing the last line to:
_control[0].value = val;
UPDATE:
It would be a lot easier if you used jQuery:
$('[name='+ctrl+']').val(val);

Related

Submitting a form through google scripts

I need to submit a form in a google script but get this error:
TypeError: Cannot call method "withItemResponse" of undefined
According to the link below, this is how it should be set up https://developers.google.com/apps-script/reference/forms/form#createResponse()
Code:
//Submit form
var formID = row[24];
var form = FormApp.openById(formID);
Logger.log(form.getId()); //returns correct ID
form.createResponse() ;
form.FormResponse.withItemResponse('Core Teachers', logSummary);
//form has only two questions, a short text and a paragraph text
form.FormResponse.submit();
form.createResponse() returns a FormResponse, which you need to assign to a variable.
also, withItemResponse() expects an object of type ItemResponse. I am not familiar with google forms, but maybe this gets you in the right direction:
var formID = row[24];
var form = FormApp.openById(formID);
var formResponse = form.createResponse();
// get items of form and loop through
var items = form.getItems();
for (index = 0; index < a.length; ++index) {
var item = items[index]
// Cast the generic item to the text-item class. You will likely have to adjust this part. You can find the item classes in the documentation. https://developers.google.com/apps-script/reference/forms/item-type.
if (item.getType() == 'TEXT') {
var textItem = item.asTextItem();
var itemresponse = textItem.createResponse('Core Teachers');
formResponse.withItemResponse(itemresponse);
}
}
formResponse.submit();
Generally, when the documentation of a method lists as parameter type something else than primitive types like String or Boolean you need to create or aquire an object of that type, like I did with createResponse. You need to familiarize yourself with these and other principles because the GoogleAppsScript documentation assumes knowledge of them.

Issue with if statement in jquery

I have a very simple application. My Home controller receives a Comment object and runs its logic to determine whether a notification needs to be displayed. If the answer is yes, then it sets the following parameters in ViewBag:
ViewBag.toDisplayNotification = 1;
ViewBag.notificationTitle = "This is the title";
ViewBag.notificationId = 2;
else, it sets the parameters as follow (I randomly set everything to null so that toDisplayNotification wouldnt be 1 anymore!)
ViewBag.toDisplayNotification = null;
ViewBag.notificationTitle = null;
ViewBag.notificationId = null;
It then displays the Comment partial View in which I have:
<script>
$(function myfunction() {
var toDisplayNotification = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.toDisplayNotification));
var notificationTitle = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.notificationTitle));
var notificationId = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.notificationId));
if(toDisplayNotification == 1){
var n = new Notification(notificationTitle, {
body: "This is where the body goes",
icon: '#Url.Action("GetImageByNotificationId", "Image", new { id = ViewBag.notificationId})'
});
}
});
</script>
So the issue I'm facing is that the view, regardless of the toDisplayNotification value, always displays the notification (I have tested the logic of my Home controller and know that it sets the correct values to each ViewBag property) even when the value of toDisplayNotification shouldnt be zero.
Is it possible that my ViewBag values are being changed somehow (can't be from the code since my Home controller displays the partial view directly so the values should remain unchanged in the transition) or am I missing something in my if condition?
Edit 1 - To answer some of the questions below. I am only using Newtonsoft.Json.JsonConvert.SerializeObject because someone in a different question had suggested that I use. Otherwise, I'm not a serialization expert (What I find is that unless, I serialize the property, I cannot pull non-integer values out of ViewBag into jquery/javascript).
Also, I did try replacing the toDisplayNotification line with either of the following but neither one worked:
var toDisplayNotification = #ViewBag.toDisplayNotification;
//or
var toDisplayNotification = #Html.Raw(ViewBag.toDisplayNotification);
Try this
var toDisplayNotification = #Html.Raw(ViewBag.toDisplayNotification);
if(toDisplayNotification == 1){
var n = new Notification(notificationTitle, {
body: "This is where the body goes",
icon: '#Url.Action("GetImageByNotificationId", "Image", new { id = ViewBag.notificationId})'
});
}
I'm not entirely sure why you are serializing ViewBag.toDisplayNotification and then comparing it to a number.

Google Script to see if text contains a value

I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');

Dynamic Spreadsheet using HTML + JavaScript only

So I've got a couple of questions. I'm attempting to create a dynamic spreadsheet, with the capabilities of having values inserted into it as well as (and only needed) being able to process the SUM() formula. The problem I've run into right now, is when inserting a value.
Firstly allow em to show the JS I have for the insertion. The HTML table is using id values of 1_1,1_2 etc.
EDIT: Fixed the var column= document.getElementById(insert); line, however it doesn't seem to want to commit any inserted value. Shouldn't it simply be a return statement to commit a change to the html field?
function insertValue() {
var v = document.getElementById("submitText");
v = v.value;
var row = document.getElementById("row");
row = row.value;
var col = document.getElementById("col");
col = col.value;
var insert = row + "_" + col;
insert = insert.toString();
var col = document.getElementById("col");
EDIT:: return column.value = v;
} //end function
When I'm attempting to take the insert variable and use it as the id value, it breaks the whole program. Should I be casting the insert var to something other then a string?
I assume
var column.getElementById(insert);
should be
var column = document.getElementById(insert);
Your line of code is invalid.
function insertValue() {
var v = document.getElementById("submitText");
v = v.value;
var row = document.getElementById("row");
row = row.value;
var col = document.getElementById("col");
col = col.value;
var insert = row + "_" + col;
// Don't really think this is necessary, so probably remove it.
//insert = insert.toString();
var column = document.getElementById(insert); // Compare this line to yours
column.value = v;
} //end function
The reason of having error is because you're not writing it correctly.
var column.getElementById(insert); is wrong syntax. var is supposed to be followed by a variable name, and you can assign an initial value to it.
It is surprising that though you got it correct in the beginning but fail to do so later.
But the next time you have an error in your JavaScript code, check the browser's JavaScript Console. It can probably be opened using F12, and inside you will see the error is shown. Then you will not need to always come up and ask a question for every single problem you met. :)

Javascript for...in loop for objetcs not running on last property

this is my first post in stackoverflow.. I am trying to iterate over an object(my implementation is an associative array) which in turn has some properties. Now I wish to construct another array out of it in order to use it as a localsource in jquery autocomplete widget for seach operations. Now the problem is that i am using for in loop to that according to the documenations available... However the output is always one less than the original object. The itearation involving the last element is not performed at all. Below is the sample object that I am using as input.
SubTeachPair = object{"5CS1":{SubAbbrev:"CA-L",SubCode:"5CS1",SubName:"Computer Architecture",TeacherId:"1",TeacherName:"Ayush Pandey",label:"Computer Architecture",value:"5CS1"},"5CS2":{SubAbbrev:"CA-P",SubCode:"5CS2",SubName:"Computer Engg",TeacherId:"10",TeacherName:"MAyush Pandey",label:"Computer Engg",value:"5CS2"}}
It has this kind of elements and is dynamically generated so the property names are variable. The loop construct that I have written is
var SubSource = [];
console.log(SubTeachPair);
var count = 0;
for(sub in SubTeachPair){
console.log(count);
SubSource[count] = {};
SubSource[count]['label']=SubTeachPair[sub]['label'];
SubSource[count]['value']=SubTeachPair[sub]['value'];
count++;
}
However, the result for the given input is only:
object{{ label: "Computer Architecture", value: "5CS1"}}
Am I missing something here?
edit-- The function that produces the input object is as follows(It is triggered onclick by the next button).
$('#' + $(this).attr("id")).autocomplete({
source : 'search',
minLength : 1,
change : function(event, ui) {
if( typeof ui.item != 'undefined') {
SubTeachPair[$(this).attr("id")] = {};
// console.log(ui.item);
SubTeachPair[$(this).attr("id")]['value'] = $(this).attr("id");
SubTeachPair[$(this).attr("id")]['label'] = $('label[for="' + this.id + '"]').html();
SubTeachPair[$(this).attr("id")]['SubCode'] = $(this).attr("id");
SubTeachPair[$(this).attr("id")]['SubName'] =$('label[for="' + this.id + '"]').html();
SubTeachPair[$(this).attr("id")]['SubAbbrev'] =$('label[for="' + this.id + '"]').attr('id');
SubTeachPair[$(this).attr("id")]['TeacherId'] = ui.item.id;
SubTeachPair[$(this).attr("id")]['TeacherName'] = ui.item.value;
// console.log(SubTeachPair);
//window.SubTeachPair = SubTeachPair;
}
}
});
I think I have found the cause of the error -- the object that is the input is actually the out put of another form that uses jquery autocomplete . Now when I enter something in the input and then click on the suggestion, the suggestion is filled in the text input, however if i do not click outside the input text and directly click the button which triggers my script, I get that error. Otherwise its fine. Is there any way to avoid that?
In your code, the array SubSource and count are not defined, You have to declare:
var SubSource = [];
var count = 0`
before for(sub in SubTeachPair) {...}
See http://jsfiddle.net/abu5C/
Try this:
SubSource[count] = {};
for(sub in SubTeachPair) {
console.log(count);
SubSource[count]['label']=SubTeachPair[sub]['label'];
SubSource[count]['value']=SubTeachPair[sub]['value'];
count++;
}

Categories