how can i access a variable in one javascript in another javascript? - javascript

Hi guys This is my code of two javascript.i want to access variable defined in first javascript into another script.
1)
<script>
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
</script>
2)
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
</script>
Now my problem is i want to access the editor defined in first javascript as
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
in second javascript.
anyone has answer of this then please help me to do so

If you leave out var while defining variables they will be globally accessible.
So
pre = this;
instead of
var pre = this;
would make pre accessible from every function.

the only way I can think is to pass the variable into the other functions as a variable
function otherJavaFile.myFunction (myVariable);
or alter a variable in the HTML i.e. the custom data-value and then the other script can access it. I don't like global variables.
// Sheet 1
$("#myDiv").attr("data-variable",yourValue);
// Sheet 2
var secondVariable = $("#myDiv").attr("data-variable");

buddy i am not comfortable with jquery...
I hope you are looking forward for the iframes/frames on same document[window sharing].
Based on my knowledge of Javascript DOM to access a variable defined in one document inside another document.You have to use document.importNode(original Node as in other document,boolean) method as per DOM 2.
Do something like this for javacript code ...
documentI(original variable/node present here)- iframe.contentDocument.getElementsByTagName(/Tag name of Node/)...
documentII(node to be cloned here)-
document.importNode(originalNode,True)
I hope this works

Related

Jquery can't pass variable through function

$(document).ready(function() {
//var audit_to_del;
//var type;
//var option_selected;
//var progress;
function redirect(audit_type) {
var page;
switch(audit_type){
case 'Simple 123':
page = 'smeg';
break;
}//end switch
return page;
}
$('#audit_summary_list_div').on("click", ".go_btn", function(e){
var audit_to_del = $(this).prev('.audit_to_del').val();
var type = $(this).closest('tr').find('.audit_type').text();
var option_selected = $(this).closest('td').prev().find('.option_select').val();
var progress = $(this).closest('tr').find('.progress').text();
var location = redirect(type);
alert(location);
});
});
If I pass a literal value through the function it works and returns 'smeg'
var location = redirect('Simple 123');
If I alert(type) the value is correctly shown as Simple 123
If I try to use
var location = redirect(type);
I get an undefined error
I have tried created global variables and then using them in the function
Your text has white-space in it making the condition false. Try that :
var location = redirect($.trim(type));

Google Script Active Cell Value and MsgBox

I am trying to get the following code to work. I want a msgbox to appear that has the value of the cell that is being edited. This should be very simple, but I cannot get it to work. Here is the code:
function onEdit(event) {
var s = event.source.getActiveSheet();
var lastColumnRow = s.getLastColumn();
var r = event.source.getActiveRange();
var editRange = s.getActiveRange();
var editCol = editRange.getColumn();
var editRow = editRange.getRow();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}
Thanks in advance!
The problem is just that you missed a pair of parenthesis after getActiveCell.
To help you find problems in functions that you cannot run directly (since you wouldn't get the event object). You can either wrap it in a try-catch, like this:
function onEdit(event) {
try {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
} catch(err) {
Browser.msgBox(err);
}
}
Or create the event object manually, and call a "test" function instead.
function testOnEdit() {
onEdit({source:SpreadsheetApp.getActive()});
}
function onEdit(event) {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}

Javascript to Read/Count Sharepoint 2010 List Items

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>
What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

Javascript: creating dynamic variables and object names. / html5 localstorage

I'm working on a form that is saved by HTML5 local storage.
When pressing save:
function saveAll(){
var field1 = document.getElementById('field1').value;
localStorage.setItem('con_field1',field1);
var field2 = document.getElementById('field2').value;
localStorage.setItem('con_field2',field2);
var field3 = document.getElementById('field3').value;
localStorage.setItem('con_field3',field3);
var field4 = document.getElementById('field4').value;
localStorage.setItem('con_field4',field4);
var field5 = document.getElementById('field5').value;
localStorage.setItem('con_field5',field5);
var field6 = document.getElementById('field6').value;
localStorage.setItem('con_field6',field6);
}
And when loading the page (fills out the forms):
function ShowAll() {
var field1 = localStorage.getItem('con_field1');
document.conditioning.field1.value = field1;
var field2 = localStorage.getItem('con_field2');
document.conditioning.field2.value = field2;
var field3 = localStorage.getItem('con_field3');
document.conditioning.field3.value = field3;
var field4 = localStorage.getItem('con_field4');
document.conditioning.field4.value = field4;
var field5 = localStorage.getItem('con_field5');
document.conditioning.field5.value = field5;
var field6 = localStorage.getItem('con_field6');
document.conditioning.field6.value = field6;
}
This all works fine, but I want to re-write this in a more fancy and efficient way. I was thinking of something like this:
function ShowAll() {
var field = [];
for (i=0; i<6; i++) {
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
}
But the browser is not enjoying this. Basically I need to create a loop that automatically changes the "field" name in to 'field1, field2, field3' etc. The window thing is working, but I'm just using it wrong.
Anyone has an idea?
Thanks a lot!
function showAll(t1,c1,d1) {
var field1 = localStorage.getItem('con_field1');
console.log(field1)
var field2 = localStorage.getItem('con_field2');
var field3 = localStorage.getItem('con_field3');
}
You should add all of your data to one object, stringify it, then add that to local storage under a single key.
When you load it, grab the one local storage item, parse it, then access the properties on the object.
e.g.
var save = function () {
var data = {
foo: 'bar'
};
localStorage.setItem('myData', JSON.stringify(data));
};
var load = function () {
var data = JSON.parse(localStorage.getItem('myData'));
var someProp = data.foo; // gives you 'bar'
};
It looks like your main problem is that the fields are indexed beginning with 1, but your loop indexes from 0.
What about this?
var field = [];
for (i = 1; i <= 6; i++)
{
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
Also, I'm not 100% on this, but I think using document.getElementByID is more cross-browser compatible than using bracket notation on the window object, but it's been a while since I wrote plain vanilla JS, so don't quote me.
I would try document.purpose["field" + i].value = window['con_field' + i].

a basic javascript class and instance using jquery "$(this)" for XML parser

I am (slowly) writing an XML parser for some "site definition" files that will drive a website. Many of the elements will be parsed in the same manner and I won't necessarily need to keep the values for each.
The XML
The parser so far
My question is actually pretty simple: How can I use jquery manipulators in an class function? How can I pass $(this)? I know that it sometimes refers to a DOM object and sometimes the jQuery object, but am a bit hazy.
For my function:
function parseXML(xml) {
$("book, site", xml).children().each(function() {
var label = $(this).get(0).tagName;
var text = $(this).text();
var key = toCamelCase(label);
if ((key in siteData) && (text != -1)){
if (isArray(siteData[key]))
{
$(this).children().each(function (){
var childLabel = $(this).get(0).tagName;
var childText = $(this).text();
var childKey = toCamelCase(childLabel);
if(isArray(siteData[key][childKey]))
{
siteData[key][childKey].push(childText);
}
else {
siteData[key].push(childText);
}
});
}
else
{
siteData[key] = text;
}
};
});
}
});
I want to place
var label = $(this).get(0).tagName; var text = $(this).text(); var key = toCamelCase(label);
in a class, so I can do something like
var child = new Element(); and var subchild = new Element();
and then use child.label , child.text and child.key...
But again, not sure how to use the jquery methods with these... I have more nodes to process and I don't want to keep doing stuff like var label = $(this).get(0).tagName; and then var childLabel = $(this).get(0).tagName;
Thanks.
var app = {};
app.element = function(data) {
return function() {
var _text = data.get(0).tagName, _label= data.text(), _key = toCamelCase(_label);
var that = {};
that.label = function() {
return _label;
}
that.text = function() {
return _text;
}
that.key = function() {
return _key;
}
return that;
}();
};
app.instanceA = app.element($(this));
document.writeln(app.instanceA.label());
Ok so this works but, I'm not sure if it's the best way.

Categories

Resources