Create java script array dynamically whose name is in java script string - javascript

I have a collection of arrays which are generated dynamically. What I am trying to do is to implement an AutoComplete functionality. I want to use those arrays in click event handler, by getting name dynamically and assigning that to local array. But that is not working (I'm not sure abt my code). Is there any way to achieve that?
Here is my code which I believe should work (which does not work):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
var ga_input1 = new Array('India','Russia','Norway');
var ga_input2 = new Array('Delhi','Mumbai','Hyderabad');
</script>
<body>
Countries: <input id="input1" type="text"/>
Cities: <input id="input2" type="text"/>
<script>
var arrayTmp = new Array();
$('input').keydown(function(){
var id = $(this).attr('id');
arrayTmp = "ga_"+id; // What I believe here is the values of ga_input1/ga_input2 are assigned to array 'arrayTmp'
//alert(arrayTmp[0]);
});
</script>
</body>

All global variables are members of the window object, so:
arrayTmp = window["ga_"+id];
But I'd personally put the data in an object like this:
data = {
'input1': ['India','Russia','Norway'],
'input2': ['Delhi','Mumbai','Hyderabad']
};
...
arrayTmp = data[id];

You can put that arrays in a "Map" and later fetch them from it easily.
Here's how it's done:
var countryMap = {};
countryMap["Europe"] = ['Russia', 'England', 'Norway'];
countryMap["America"] = ['USA', 'Canada', 'Mexico'];
....
var arrayTmp = countryMap["America"];
alert(arrayTmp[0]); //USA
alert(arrayTmp[1]); //Canada
alert(arrayTmp[2]); //Mexico

What you have in arrayTmp is just a string "ga_input1". Instead, try eval("arrayTmp=ga_"+id);.

eval('var arrayTmp = ga_' + id);
alert(arrayTmp[0]);

Related

How to pass values to an external Javascript script from ASP.NET

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.

adding a new Document method that returns new computed style

Is there a way to add a new Document method?
I try researching this on google but it only shows how to make your own js object and add a method on it.
This is my code:
<html>
<head>
<script>
document.prototype.atvalue = function atvalue(arg)
{
var newType = window.getComputedStyle(this, null).getPropertyValue(arg);
return newType;
};
</script>
</head>
<body>
<p style="font-size: 100px"> help </p>
</body>
</html>
Given:
SomeConstructorFunction.prototype.foo = something;
Then foo will be a property of instances of that function:
var something = new SomeConstructorFunction();
something.foo();
document is not a constructor function.
If you want to add a property to an object then … just add it to that object:
document.foo = something;
You cannot create a document prototype function, but you can create a custom document method by:
document.something = function(){};
and by calling it:
document.something();

Adding object to my array of objects using javascript functions

So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
Array#push adds items to the end of an array. eg: arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
to append to an array you can use push
list.push({name:"sudarshan",rno:"33"});
or just
list[list.length] = {name:"sudarshan",rno:"33"};
which is the same as above.

Parse xml tag attributes using Javascript or Jquery?

I have one xml. Example XML is given below
<company sample="text">
<employee id="001" sex="M" age="20">Premshree Pillai</employee>
</company>
I need to get company attribute sample value
I am trying this method
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).find('company').attr('sample');
alert(pic);
};
</script>
Its Shows Undefined in my alert box.
But i can also alert this child tag its working
var pic = $(currLoanXml).find('employee').attr('id');
alert(pic);
What is a problem. I need to get first tag attributes. Please help me.
you need to use filter() instead of find() here because company is the root element, ie currLoanXml refers to the company element. find will look for decedent elements only
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).filter('company').attr('sample');
alert(pic);
Demo: Fiddle
You go too deep
$(function() {
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var sample = $(currLoanXml).attr('sample');
console.log(sample);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Using myFuncArray.shift()() to call functions

I am having troubles using shift() to call functions I have put in an array. I have put together a simple example illustrating the problem.
Essentially the function gets called, however, the changes to variables in the function do not stick.
<html>
<head>
<script type="text/javascript">
Taco = function() {};
Taco.prototype.init = function() {
this.ex1 = "ex1 in init()";
alert(this.ex1);
};
</script>
</head>
<body>
<input type="Submit" onClick="withShift();" value="withShift"/>
<div id="div1">
</div>
<input type="Submit" onClick="noShift();" value="noShift"/>
<div id="div2">
</div>
<script type="text/javascript">
// This calls init but does not hold the value of ex1 after the call
withShift = function() {
taco = new Taco();
funcQ = [];
funcQ.push(taco.init);
funcQ.shift()();
div1 = document.getElementById("div1")
div1.appendChild(document.createTextNode(taco.ex1));
};
// this calls init and it holds the value...
noShift = function() {
taco2 = new Taco();
taco2.init();
div1 = document.getElementById("div2")
div1.appendChild(document.createTextNode(taco2.ex1));
}
</script>
</body>
</html>
Thank you in advance for any suggestions.
JavaScript does not remember the this argument when you pass method pointers. You have to use the call or apply method on the function object to explicitly pass this.
Using taco.init is roughly the same as using Taco.prototype.init when it comes to passing function pointers. Here's what would be the working way:
taco = new Taco();
funcQ = [];
funcQ.push(taco.init);
// pass taco first, and the non-hidden function arguments after;
// in this case, no other argument
funcQ.shift().call(taco);
If you can't use this kind of syntax, you may use anonymous functions:
taco = new Taco();
funcQ = [];
funcQ.push(function() { taco.init(); });
funcQ.shift()();
In opposition to the object.method syntax that doesn't carry the this argument, closures are reliable.

Categories