Jquery can't pass variable through function - javascript

$(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));

Related

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

JavaScript and jQuery code to return function by var

I am working on small api to get content from my database. I want to show data in a JavaScript/jQuery function according to variables I declared.
example
<script>
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
ver version = "1.00";
this.return url;
this.return name;
this.return version;
}
</script>
How I intend to use it
<script>
minapi = new dataset();
//here I want to return only name
alert(minapi.name);
</script>
Please any idea of how to get this done?
In addition, is there a way to create jQuery function to execute once page load without using this $( document ).ready(function() {});?
I think you want this:
function dataset() {
var myData = {
url: "www.example.com",
name: "mini api",
version: "1.00"
};
return myData;
}
var myVar = dataset();
console.log(myVar.name);
JSFiddle: https://jsfiddle.net/1455d5z3/
This is what you are attempting to do. I fixed ver and assigned properties correctly.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.url = url;
this.name = name;
this.version = version;
}
There might be better ways to do this depending on your situation, but this does give the result you want.
Please use like this.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.returnUrl = function (){
return url;
}
this.returnName = function (){
return name;
}
this.returnVersion = function (){
return version;
}
}
var minapi = new dataset();
alert(minapi.returnName());
Refer Fiddle

how can i access a variable in one javascript in another 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

Getting URL data with JavaScript (split it like php $_GET)

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

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