Javascript, HTML, and iFrames - javascript

We have a web based type application which controls workflows for my place of business. Setting up how each user interacts with the application (Basically a web page) is a pretty straight forward process. We have the option of adding iframes into the layout.
I have written a very basic bit of javascript which sits inside an onChange function (part of the program) the script just calculates some numbers together and returns the value in a field.
What I am trying to do is get that total sum into an iframe instead of a form/element (?)
I understand this isn't very clear but is hard to go into great detail for company policy reasons.
Information is taken and calculated
for (var i = 0; i < grid.contentWindow.GetRowCount(); i++)
{
Numof = grid.contentWindow.GetSingleColumnValue(i, 'info').replace(re, "");
total = parseFloat(Numof) - total;
And is printed out into a pre created field using
CF_SetFieldValue("Printed_Field", dec_ToDecimalValue(total.toString(), 2));
Question is: how do I get the information to print in the iframe instead of "Printed_Field"?
Sorry for the lengthy and randomish post. any help would be much appreciated.
Edit: I guess at the most simplest question - How do I get the information in the forms into the inframe instead? (To be displayed in a table)

That depends on how CF_SetFieldValue is defined. By the looks of it there's a lot of very strange and probably superfluous functions that get in the way of easy-to-read-and-understand code.
Probably what you need is something like grid.contentDocument.getElementById('Printed_Field').value = dec_ToDecimalValue(total.toString(),2);

Related

How to get checked property's value from passed control id in javascript function?

So I have this JS script:
<script>
function getCheckedProperty(obj,args)
{
if(document.getElementById("<%=checkbox1.ClientID %>").checked)
return true;
else
return false;
}
</script>
This only works for checkBox1. I want to be able to pass control id from parameters, so that it can return value of passed control. Also, please, respond with the usage.
<asp:CustomValidator runat="server" ClientValidationFunction="getCheckedProperty()></asp:CustomValidator>
TIY. SRJ.
Check this question it might have your answer.
if I get it right you want to get ids dynamically for example checkbox1, checkbox2,...
You can add the dynamic part to the id like this:
for (var i = 1; i < n; i++) {
var id = "checkbox" + i;
var ch = document.getElementById(id);
if (ch.checked == false)
return false;
}
return true;
Unfortantly, this is a real problem. The control name(s) are generated at runtime, and ALSO THIS:
document.getElementById("<%=checkbox1.ClientID %>")
So at page render time, the .net pre-processor will SWAP out the <% %> at render time.
this is also why you can't say have the js code in a external library and expect this to work.
However, your DEAD OBVIOUS question remains. Stuff a name into a simple variable and use that to get the control. After all, we can't and would not want to HARD code the value as per above, and it would be beyond silly to assume we ONLY have a means to HARD code references to controls.
So, you want of course this:
var MyControl = 'Checkbox1';
var ckBox = document.getElementById(MyControl);
if (ckBox.checked)
alert('Check box ' + MyControl + ' is checked!');
else
alert('Check box ' + MyControl + ' is UN-checked');
Now in fact the ABOVE can and will work if you force the control name generation as static.
so, here is the markup:
<asp:CheckBox ID="CheckBox1" runat="server" ClientIDMode="Static" />
So, if you ARE able and ARE willing to use ClientIDMode static, then the .net processing will NOT re-name your control. As a result you can do this:
var MyControl = 'Checkbox1';
var ckBox = document.getElementById(MyControl);
Or, even this (as HARD coded)
var ckBox = document.getElementById('CheckBox1');
Or even this:
var ckbox2 = document.getElementById(<%= CheckBox1.ClientID %>);
Now, the last one above? Well, we ARE useing the .net pre-processor to swap out the name - but it will still work - and clientID will not be changed - but the pre-processor is STILL involved.
AGAIN: the <%= 'SomeControlName.ClientID%> ONLY works because this expression is SWAPPED out at runtime by the .net web page pre-processor. This occures BEFORE the js code is run.
So you can NOT use a variable in the above <%=%> expressions since the js code HAS NOT even run and the new js code has not even been generated at this point in time.
In effect, you would (have to) do a PAGE search for the control. If you can NOT adopt ClientIdMode="static", then you MUST SEARCH the page.
You can write your OWN search routines - kind of like adopting a nice road to world poverty, or you bite the bullet, and adopt a library that WILL do the heavy lifting for you.
So, without using (forcing) StaticID on the control? then you now have to accept the BIG HUGE LARGE MASSIVE decision and introduce jQuery into your application.
jQuery is able to scour and search and look and loop and find that control for you on the web page. This is a cost not without processing cost, and not without a big speed penalty.
So, without staticID's, then you can adopt jquery and do this:
<script src="Scripts/jquery-3.5.1.js"></script>
<script>
// so if you decide and adopt jQuery, then it can do the searching for you
// BUT YOU ARE now adopting and committing to a whole new js library
// so, with jQuery we cna do this:
function jstest2(){
var ckbox2 = $('#CheckBox1');
var ckboxdom = ckbox2[0];
alert('status of check box = ' + ckboxdom.checked);
// of course the above is STILL hard code
// get control by runtime or NON hard code
// get (search) for check box based on control name in
// a variable
var MyCheckBox = 'CheckBox1';
var ckbox3 = $('#' + MyCheckBox);
var ckboxdom3 = ckbox3[0];
alert('status of check box = ' + ckboxdom3.checked);
</script>
I found after doing a nuget of jQuery, the fans on my laptop became too hot to even keep on my lap. But, things did settle down, and eventually the VS editors caught up, and things did settle down.
Also keep in mind that you have to re-learn how to reference a simple control.
eg:
<script>
function getbox() {
var tbox = document.getElementById('TextBox1');
alert(tbox.value);
// jQuery example
var tbox2 = $('#TextBox1');
alert(tbox2.val());
}
</script>
So notice now, how the long time js standard and approach is "value" as a property?
Well, now you using .val() that is a function (method) of that search result. So just keep in mind that by adopting jQuery, then all of your code that needs to get simple values from controls has to under go a syntax change, and you as a developer will have to re-lean how to reference a simple control with new syntax. The check box is a great example - it now becomes a array, and you use that array to get at the checked property.
And same in above for a simple grab of a value from a text box.
Notice how the syntax and approach to getting the value of the text box NOW has changed!!!! So you need a cheat-sheet since simple things like value now become .val().
And the same changes occur for say a label on a web page (again syntax changes).
You will ALSO notice that the results of the check box example are an array!!! So we had to drill down into the resulting array[] to get the "checked" value.
Of course how big of a deal your code changes are by adopting jQuery? Well, it depends, on relative medium sized or even a small project? $20,000 was budgeted and we still changing things.
On larger projects you simply need more manpower and would add another zero to the above cost to adopt jQuery.
However, jQuery is now widespread used, and it will do the "dirty work" of searching the DOM for you, and if you need runtime resolution as opposed to compile time resolution to find a simple control on a web page, then jQuery is probably your best choice. And I find that jQuery is really nice for ajax calls - so while it is a big change, it still well worth the effort to adopt the jQuery library and risk introducing this framework into your existing projects.

How to use javascript split in Qualtrics

Very new to Javascript and have been searching the webs for assistance, but haven't quite found a solution.
I am attempting to use javascript to split/remove the output of a particular field. The data in the survey is being pulled from our school's database after a user logs in to the survey via shibboleth. All the information is being displayed, so that part works, but one particular field is appending an email address (#email.com) to a field.
I want to omit this part from being displayed. Either my javascript is incorrect or the javascript is not being loaded/read. The javascript code was borrowed from a colleague and it works on his surveys, but he has a lot of other things going on in his survey and this works for him.
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
var iid = "${e://Field/theUTIID}";
var split_array = iid.split("#",1);
var eid = split_array[0];
Qualtrics.SurveyEngine.setEmbeddedData('theUTIID', eid);
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
var iid = "${e://Field/theUTIID}";
var split_array = iid.split("#",1);
var eid = split_array[0];
Qualtrics.SurveyEngine.setEmbeddedData('theUTIID', eid);
});
I have this in both the Onload and OnReady for testing. Doesn't matter if I have this is one location or the other, I am not getting the desired results.
I only have one question on the survey (it's just a test survey) and so the javascript code is with the first and only question.
Survey Question has the following in a text entry. Again, output is displayed, but need the #email.com to removed from the EID field.
The code looks correct (other than it only needs to be in one or the other function). I'm guessing it isn't a problem with the code, but where you are trying to pipe the embedded variable. The JavaScript above has to be attached to a question on a separate page before the place where you want to pipe it.
Add a page break, then pipe theUTIID into a question on the next page.

sharepoint Online/365 Jquery, Set Lookup Column Not working e.i ($("select[Title='Column']")

I've been doing some work on Sharepoint Online/365 and have got stuck trying to set the value of a lookup or choice column in NewForm.aspx
Narrowed my problem down to not being able to set lookup/Choice Columns
I have simplified a code on my page down to
//Phase being a Choice Column & Closure a case sensitive valid option
$("select[title='Phase']").val("Closure");
//ProjectName being a Lookup Column & Test2 a case sensitive valid entry in the list
$("select[title='ProjectName']").val("Test2");
I have no problem setting text fields as the following code works fine on a text field I created
$("input[title='TextField']").val("Test2");
I have used the following Jquery libraries 1.7.2/min.js and 1.11.3
Not sure whether you used _spBodyOnLoadFunctionNames.push() method for your logics. Usually you have to wait all SharePoint DOM objects are loaded and then to execute your jQuery code. If you used SharePoint JavaScript library, you probably needs to call ExecuteOrDelayUntilScriptLoaded() to make sure your call is called after curtain SharePoint .js files are loaded.
First Thanks "Verona Chen" and " DIEGO CARRASCAL" because of who i've learnt a few other tricks in SharePoint which will help with other projects.
My original script before the question was trying to use a query string to populate a field in newform.aspx (which i have done on sharepoint 2013 with code i have found here on)
Unforuntaly with sharepoint online/365 This code was no longer working.
This code has fixed my issue (though it does change how a few previous pages are constructed)
Appologies if this doesn't directly answer the above question (as this was me trying to breakdown the overall issue i was having into something simpler and easier to address based on me narrowing down the issue in my original code) however as I am now up and running, it seems only polite to post the outcome.
Prior to code, i have a projects list with a "ProjectName" field. I was sending the field name into a URL and querystring to get mylist/newform.aspx?ProjectName=Test2
I was then trying to pull that Test2 into the lookup field (liked to the project list) "ProjectName" in the list "MyList"
But even when loading the function for my old script with _spBodyOnLoadFunctionNames.push() it wasn't working.
After playing with this for a while and after some looking around i found this peice of code
<script type="text/javascript">
(function () {
var ctx = {};
ctx.Templates = {};
ctx.Templates.Fields = {
'ProjectName': {
'NewForm': renderTaskCategory
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();
function renderTaskCategory(ctx) {
//extract cat parameter from a query string
var GetProjID = GetUrlKeyValue('ProjID');
//set lookup field value
ctx.CurrentFieldValue = GetProjID;
//default template for rendering Lookup field control
return SPFieldLookup_Edit(ctx);
}
</script>
This means that i have to change my previous url builds to create mylist/newform.aspx?ProjID=2
This script then finds item ID 2 (which happens to be test2 in this case) and puts the title of item 2 in my lookup field ProjectName
Thanks again to those that helped earlier.
And apologies again if this doesn't directly answer the question i originally asked.

javascript / omniture - how to clear all properties of an object (s object)

I'm using omniture and tracking various properties to the "s" variable for tracking. The example code I'm following calls a function called s.clearVars() after each tracking event. But I get an error saying that clearVars is not a valid function. Does anyone know what I'm supposed to call to clear the tracking object? Or how to clear all properties from a javascript object.
Don't clear the entire s object, it contains a lot of functions that are listening to dom events and if you clear those, you'll lose a lot of functionality. I'm guessing you just want to clear all of the custom variables that you are populating on the page (props, evars, events, products, etc). The s.clearVars function is a "plugin" that Omniture consulting wrote that clears all of these values for you. You could contact your Omniture Account manager and ask him for the code, he may or may not give it to you, depending on whether he wants to sell you some consulting hours or if he knows what you are talking about, or you could do this yourself with a couple of simple loops:
function ClearVars(){
for (var i=0; i < 75; i++) {
s['prop'+i]='';
s['eVar'+i]='';
if(i<=5)
s['hier'+i]='';
}
svarArr = ['pageName','channel','products','events','campaign','purchaseID','state','zip','server','linkName'];
for (var i=0; i < svarArr.length ; i++) {
s[svarArr[i]]='';
}
}
Please note I haven't tested the code. Just shot it from the hip.
Small Correction to Vector Frogs (amazing) code.
The second for loop need to have i=0 to clear out the pageName variable.
Great Script V_FRog!
this will reset the entire object as per your original request:
s=s_gi(s_account);
I think the best answer for how to clear the properties off of a JS object is to just create a new object all together.
Check out this post: How to quickly clear a Javascript Object?
s = {};

ASP.NET inline server tags

I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.
So I have code like this in my .aspx file:
function EditRelationship() {
var projects=<%= GetProjectsForEditRelationship() %>;
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
var rels=<%= GetRelationshipsForEditRelationship() %>;
// etc
}
Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.
I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).
So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.
If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?
Create a ASP:HiddenField control, set its ClientIdMode to "Static"
Assign the value of GetRelationshipsForEditRelationship() to this field on page load
In your javascript, read the value from the hidden field instead, I assume you know how to do this.
It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)
You could do this from your page in the code-behind
ClientScript.RegisterArrayDeclaration("projects", "1, 2, 3, 4");
or to construct something like JSON you could write it out
ClientScript.RegisterClientScriptBlock(GetType(), "JSONDeclarations", "your json stuff");
UPDATE Based on my comment
<script id="declaration" type="text/javascript">
var projects=<%= GetProjectsForEditRelationship() %>;
var rels=<%= GetRelationshipsForEditRelationship() %>;
</script>
<script type="text/javascript">
function EditRelationship() {
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
}
</script>
I don't have VS2008 installed to test with, so take this with a grain of salt, but have you tried something like this?
var projects = (<%= GetProjectsForEditRelationship() %>);
Something like that might trick the JavaScript parser into ignoring the content of your expression.
For what it's worth, VS2010 correctly parses and highlights your original code snippet.
Is it an option to move this to VS2010? I just copied and pasted your code and the IDE interpreted it correctly.
The best solution is to put javascript in a separate file and avoid this entirely. For this particular function, you're doing server-side work. Why not build the list of options that you intend to add dynamically in codebehind, put them in a hidden div, and then just have jQuery add them from the already-rendered HTML?
If you have a situation where you really want to dynamically create a lot javascript this way, consider using ScriptManager in codebehind to set up the variables you'll need as scripts and register them, then your inline script won't need to escape
ScriptManager.RegisterClientScript("projects = " + GetProductsForEditRelationship());
(Basically, that is not the complete syntax, which is context dependent). Then refer to "projects" in your function.
(edit)
A little cleaner way to do this on a larger scale, set up everything you need like this in codebehind:
string script = "var servervars = {" +
"GetProductsForEditRelationship: " + GetProductsForEditRelationship() +
"GetRelationshipsForEditRelationship: " + GetRelationshipsForEditRelationship() +
"}"
and refer to everything like:
servervars.GetProductsForEditRelationship
If you do this a lot, of course, you can create a class to automate the construction of the script.

Categories

Resources