473,805 Members | 2,077 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

variable in object string

sorry for the stupid question, bu6 I haven't been able to find the
answer anywhere..

consider this useless function which assigns an object to a var..

function(myPara m){
var select1 = document.myForm .mySelectName;
}

I simply want this line to subsitute "mySelectNa me" with a var string

function(myPara m){
var select1 = document.myForm .myParam;
}

It doesn't work, ive tried umpteen variations with []+ "" '' etc..
How would I do this stupid-simple thing?
Jul 23 '05 #1
22 1617


bmgz wrote:

function(myPara m){
var select1 = document.myForm .myParam;

var select1 = document.myForm .elements[myParam];

but in most cases you can simply pass around objects like for instance
the form or select itself, there is hardly the need to pass in a string
to use it to find an object reference.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
VK
Each object inherits hash (associative array) mechanics, this is how
objects properties are stored. So:

function f1(propertyName ) {
var myVar = someObject[propertyName];
// in the particular:
// var myVar = document.formNa me[propertyName];
}

Jul 23 '05 #3
bmgz wrote:
[...]

function(myPara m){
var select1 = document.myForm .myParam;
}

It doesn't work, ive tried umpteen variations with []+ "" '' etc..
How would I do this stupid-simple thing?


Are you passing an object or a string?

Mick
Jul 23 '05 #4
Mick White wrote:
bmgz wrote:
[...]

function(myPara m){
var select1 = document.myForm .myParam;
}

It doesn't work, ive tried umpteen variations with []+ "" '' etc..
How would I do this stupid-simple thing?

Are you passing an object or a string?

Mick

An object, I want to know how to refer to the object that triggered the
function?
Jul 23 '05 #5
bmgz wrote:
Mick White wrote:
bmgz wrote:
[...]

function(myPara m){
var select1 = document.myForm .myParam;
}

It doesn't work, ive tried umpteen variations with []+ "" '' etc..
How would I do this stupid-simple thing?


Are you passing an object or a string?

Mick


An object, I want to know how to refer to the object that triggered the
function?

oh um, from within the function itself..
ie.

function(){
var a = "[the object that called me ie. myButton]";
}

<input type="button" name="mybutton" onclick='functi on();' />
Jul 23 '05 #6
bmgz wrote:
[...]
An object, I want to know how to refer to the object that triggered
the function?


oh um, from within the function itself..
ie.

function(){
var a = "[the object that called me ie. myButton]";
}

<input type="button" name="mybutton" onclick='functi on();' />


You have to pass a reference in your onclick:

<input type="button" name="mybutton" onclick="functi on(this);" />

in the script of your onclick use 'this' ---------------^^^^
Then in your function:

function( a ){
alert( 'the object that called me is ' + a );
...
}

or

function(){
alert( 'the object that called me is ' + arguments[0] );
...
}

--
Rob
Jul 23 '05 #7
VK
> want to know how to refer to the object that triggered the function?
from within the function itself..


Oh I see now... It depends on how your function was called: by event
capturer or by another function during normal program flow.

If by event capturer, then you simply *cannot* do it.
At least nothing reliable that would work for all browsers. You can do:

function myFunction(e) {
// "e" argument is important placeholder
// in case of working in NN/DOM event model
// IE sets global "event" variable for you
var myCaller = (e)? e.currentTarget : event.srcElemen t;
}

Of course you have to add event capturers programmically in this case.
You cannot do <element onclick="myFunc tion()">,
Empty parenthesis will kill the "e" and the script will fail for FF &
Co
You have to:
obj.onclick = myFunction;
or
using addEventListene r (DOM) / attachEvent (IE) methods

This works fine as long as there is no more elements below the element
that capturing events. Otherwise all this mess fails onto the ground.
In FF you still can get the right object by using currentTarget. But in
IE event.srcElemen t will point to the first element in the bubble
history. So in the majority of situations your only option is to use
intrinsic capturers and "manually" forward the right object to the
function: <element onclick="myFunc tion(this)">

If your function is called by another function during normal program
flow, you can check the caller property.
function myFunction {
if (myFunction.cal ler != null) {
myCaller = myFunction.call er
}
else {
// I'm the first one!
}
}

P.S. There is a lot of bubbles in docs about "caller is deprecated".
But deprecation doesn't mean "removal", it means "substituti on". As
long as *no one* provided a reasonable substitution for caller, we just
keep using it. It's supported by all main browsers.

Jul 23 '05 #8
On 19/06/2005 12:58, VK wrote:
want to know how to refer to the object that triggered the function?
from within the function itself..

[snip]
If by event capturer, then you simply *cannot* do it.
Of course you can.

<... onclick="myFunc tion(this);">

function myFunction(elem ent) {
/* The element argument is a reference to the HTML element */
}

Or:

<... id="myElement" >

document.getEle mentById('myEle ment').addEvent Listener(
'click',
function() {
/* The this operator refers to the HTML element, myElement */
},
false
);

Or:

<... id="myElement" >

document.getEle mentById('myEle ment').onclick = function() {
/* The this operator refers to the HTML element, myElement */
};
function myFunction(e) {
[...]
var myCaller = (e)? e.currentTarget : event.srcElemen t;
}
You've been told before that referring directly to the event identifier
is not wise as it could be undefined in some browsers. Refer to it via
the global object and test that it exists.

Also, the above could produce very wrong results: the currentTarget and
srcElement properties refer to very different things. The former is the
same as the element variable or the this operator in my examples, whilst
the latter (and the target property) refer to the original element that
fired the event.
Of course you have to add event capturers programmically in this case.
You cannot do <element onclick="myFunc tion()">,
Empty parenthesis will kill the "e"
So instead, one could write:

<... onclick="myFunc tion(event);">

or to be really cautious:

<... onclick="myFunc tion(('object' == typeof event) && event);">

The first argument to myFunction will either be false or an event object.

[snip]
P.S. There is a lot of bubbles in docs about "caller is deprecated".
But deprecation doesn't mean "removal", it means "substituti on".
Deprecation often means this feature may be removed in the future, and
more generally, this feature should not be used.

As far as ECMAScript is concerned, the caller property has never
existed, which is potentially a bigger concern than whether or not it is
deprecated.

Finally, the caller property doesn't provide the information that the OP
wants, at least as I understand the problem.
As long as *no one* provided a reasonable substitution for caller, we just
keep using it.


If a function must really need to know what called it, then it should
have a required argument that contains a reference to the relevant
function object. No-one needs to provide a substitute for the caller
property as it isn't necessary.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
VK
>> from within the function itself.

That was the keyword in OP. The "manual feeding" of the right object
was already given by RobG.
But what if we need to keep our HTML/XML code and scripting totally
separate?
The code below illustrates the problem many posters in this group
really encounting (even w/o knowing it):

<html>
<head>
<title>Event target</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script type="text/javascript">
function init() {
document.getEle mentById('DIV1' ).onclick = f1;
}

function f1(e) {
var myTarget = ((e)&&(e.curren tTarget))?
e.currentTarget : event.srcElemen t
alert(myTarget. id);
}

window.onload = init;
</script>
</head>

<body>
<div id="DIV1">DIV 1
<span id="SPAN1">SPA N 1</span>
</div>
</body>
</html>

Click on "SPAN 1" (nested element). FF still works properly grace to
the e.currentTarget property. This is actually why you should not use
e.target unless you're making some event tracking.
e.target will fail in any more or less complicated situation.

event.srcElemen t shows as before the original event source (SPAN1).
There is *no* way to tell from the function itself that the actual
event capturer is DIV1. The only side walk is using closures with
memory leak in IE.

You find a way (w/o closures, w/o inline "helpers") - you'll be better
than the whole Microsoft. ;-)

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
25424
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have the properties: mode1, mode2, and mode3. This seems simple but I can't quite figure it out... Any ideas anyone?
3
3649
by: XenofeX | last post by:
How can i call to object from string variable ? For instance string x = "textBox1"; i want to call the object which name is stored in the x string variable. The most important thing is the object type is unknown. x may be stored "comboBox1". I think Activator.CreateInstance makes it but how ?
41
10682
by: Miguel Dias Moura | last post by:
Hello, I am working on an ASP.NET / VB page and I created a variable "query": Sub Page_Load(sender As Object, e As System.EventArgs) Dim query as String = String.Empty ... query = String.Format("SELECT * FROM dbo.documents WHERE ") & query End Sub
4
4245
by: Andres | last post by:
Hi all, I have the problem to assign a variable of type object to a specific class at runtime. I want to use a string variable that specify the class a want to set this object. Is something similar to add a new control to a form using the controls collection: Private Sub CommandCreateInstance_Click()
11
3569
by: JohnR | last post by:
I'm trying to find a way to create a variable of a given type at runtime where I won't know the type until it actually executes. For example, dim x as object = "hi" x is declared as an object but x.gettype returns 'string', so it knows it contains a string. If I want to create a variable "y" as the same type that variable x contains how would I do that without having to iterate thru every possible
23
19208
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
6
4268
by: Neo Geshel | last post by:
I am trying to deal with an image in code-behind. I consistently get the following error: Server Error in '/' Application. Object variable or With block variable not set. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object variable...
6
14225
by: Jody Gelowitz | last post by:
I have run into an issue with variable scope within an XSLT document that is translated in VS.NET 2.0. Under VS.NET 1.1 (XslTransform), this code works fine. However, when using VS.NET 2.0 (XslCompiledTransform), the exact same XSLT transformation fails with the error: System.Xml.Xsl.XslLoadException: The variable or parameter 'lastrecordwaskit' was duplicated within the same scope. An error occurred at (174,12). at...
4
3449
by: Don Miller | last post by:
I am using a Session variable to hold a class object between ASP.NET pages (in VB). In my constructor I check to see if the Session variable exists, and if it doesn't, I create one and populate it with "Me". But if the Session variable already exists, I would like the new object be populated with everything from the object stored in the Session variable. Ideally, I'd like to retrieve the object from the Session variable and assign it to...
3
2048
by: RSH | last post by:
Hi, I have a situation where I have created an object that contains fields,properties and functions. After creating the object I attempted to assign it to a session variable so i could retrieve the information it contained on another page. This was significant because I am initially loading the data from the database, then storing relevent information in the object, I am allowing users to change the data then preview the modifications...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10609
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10360
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9185
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5542
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.