473,387 Members | 1,548 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to set a variable to a not modifying string expression using a variable

I'd like to set a variable called 'FocusIsOn' if a button got the focus.
Because my button is dynamically created I do it like
xelement = document.createElement("input")
xelement.type = "button"
element.onfocus = function() {FocusIsOn = "Button_1"; alert(FocusIsOn)}

That works great. If the button gets the focus, I got a message box saying
'Button_1'.

However, if I set the variable 'FocusIsOn' dynamically (using a variable
'ButtonNumber') like
xelement = document.createElement("input")
xelement.type = "button"
element.onfocus = function() {FocusIsOn = "Button_" + ButtonNumber;
alert(FocusIsOn)}
it doesn't work like I wish it would.

I want that 'FocusIsOn' is set to 'Button_1' if 'ButtonNumber' is '1' and if
'ButtonNumber' is '99' to 'Button_99'.
However 'FocusIsOn' is effectively set to "Button_" + ButtonNumber.
That means, it doesn't matter which button I click, the message box always
says 'Button_' plus the actual value of 'ButtonNumber'.

Does anyone know how to set a variable like 'FocusIsOn' to a not modifying
string expression?
Stefan
Oct 31 '05 #1
9 1828
Stefan Mueller wrote:
I'd like to set a variable called 'FocusIsOn' if a button got the focus.
Presumably you intend it to be a global variable.

[snip] However, if I set the variable 'FocusIsOn' dynamically (using a variable
'ButtonNumber') like
xelement = document.createElement("input")
xelement.type = "button"
element.onfocus = function() {FocusIsOn = "Button_" + ButtonNumber;
alert(FocusIsOn)}
it doesn't work like I wish it would.

I want that 'FocusIsOn' is set to 'Button_1' if 'ButtonNumber' is '1' and if
'ButtonNumber' is '99' to 'Button_99'.


Try the following:-

OPTION 1 - CREATE AN ATTRIBUTE

function MakeButton(nButtonNumber)
{
var xelement = document.createElement("input")
xelement.type = "button"
xelement.type = "button"
xelement.setAttribute("button_number",nButtonNumbe r);
xelement.onfocus = ButtonFocus;
return xelement;
}

function ButtonFocus(e)
{
var ev=e||window.event;
var e=ev.target||ev.srcElement;
var n=e.getAttribute("button_number");
FocusIsOn = "Button_" + n;
alert(FocusIsOn)
}

OPTION 2 - USE A CLOSURE

function MakeButton(nButtonNumber)
{
var xelement = document.createElement("input")
xelement.type = "button"
xelement.type = "button"
xelement.setAttribute("button_number",nButtonNumbe r);
xelement.onfocus = MakeFocusHandler(nButtonNumber);
return xelement;
}

function MakeFocusHandler(nButtonNumber)
{
return function()
{
FocusIsOn = "Button_" + nButtonNumber;
alert(FocusIsOn);
};
}

Julian

Oct 31 '05 #2
Zif
Stefan Mueller wrote:
I'd like to set a variable called 'FocusIsOn' if a button got the focus.
Because my button is dynamically created I do it like
xelement = document.createElement("input")
xelement.type = "button"
element.onfocus = function() {FocusIsOn = "Button_1"; alert(FocusIsOn)}

That works great. If the button gets the focus, I got a message box saying
'Button_1'.

However, if I set the variable 'FocusIsOn' dynamically (using a variable
'ButtonNumber') like
xelement = document.createElement("input")
xelement.type = "button"
element.onfocus = function() {FocusIsOn = "Button_" + ButtonNumber;
alert(FocusIsOn)}
it doesn't work like I wish it would.
You have created a closure so that the value of ButtonNumber is
whatever it was when the function ended. So if you used a for loop to
create the buttons with say i=0; i<100 then ButtonNumber will be 99.

I want that 'FocusIsOn' is set to 'Button_1' if 'ButtonNumber' is '1' and if
'ButtonNumber' is '99' to 'Button_99'.
However 'FocusIsOn' is effectively set to "Button_" + ButtonNumber.
That means, it doesn't matter which button I click, the message box always
says 'Button_' plus the actual value of 'ButtonNumber'.

Does anyone know how to set a variable like 'FocusIsOn' to a not modifying
string expression?


One way is to call an external function to set the ButtonNumber value
(as per Julian's post), another is to set the ButtonNumber as part of
the button ID and not within the anonymous onclick function:
...
var oBut;
for (var i=0; i<100; i++){
oBut = document.createElement('input');
oBut.type = 'button';
oBut.value = 'Show focus';

oBut.id = 'Button_' + i;
oBut.onclick = showFocus;

// Set the rest of oBut's attributes
// Add it to the document
}
...
}

function showFocus()
{
var msgDiv = document.getElementById('msgDiv');
if(this.id) {
msgDiv.innerHTML = 'Focus is on '+this.id;
} else {
msgDiv.innerHTML = 'Focus is on an anonymous '+this.nodeName;
}
}

...

<div id="msgDiv"></div>
[...]

Incidentally, the idea of Julian's of setting a custom attribute is
not supported by all browsers. It is much better to use a standard
attribute such as id or (for an input element) the name

--
Zif
Oct 31 '05 #3

Zif wrote:
Incidentally, the idea of Julian's of setting a custom attribute is
not supported by all browsers. It is much better to use a standard
attribute such as id or (for an input element) the name


I would second that.

Julian

Oct 31 '05 #4
Thanks a lot for your suggestions and solutions.

Today I tried a different approach:

1. Store the command to a string variable
xelement = document.createElement("input")
xelement.type = "button"
var tempeval = "xelement.onfocus = function() {FocusIsOn = 'Button_" +
ButtonNumber + "'}"

2. Execute the string variable
eval(tempeval)

I think this is quite easy and it works.

Many thanks again
Stefan
Oct 31 '05 #5
Stefan Mueller wrote:
Thanks a lot for your suggestions and solutions.

Today I tried a different approach:

1. Store the command to a string variable
xelement = document.createElement("input")
xelement.type = "button"
var tempeval = "xelement.onfocus = function() {FocusIsOn = 'Button_" +
ButtonNumber + "'}"
xelement.id = 'B' + ButtonNumber;
xelement.onfocus = function (){
FocusIsOn = 'Button_' + this.id.replace(/B/,'');
};

Avoids eval and closure (and hence IE memory issues).

If you are using the id attribute already and can't easily trim some
string from it to get the number, then use name, or class, or any
suitable standard attribute.

2. Execute the string variable
eval(tempeval)
Then why not:

eval("xelement.onfocus = function() {FocusIsOn = 'Button_"
+ ButtonNumber + "'}");

But it's a kludge purely to avoid an inconvenient closure.

I think this is quite easy and it works.


That 'it works' is not sufficient - using eval is almost never
necessary, and is not needed here.

While 'eval' is very powerful it is extremely wasteful of browser
resources. It requires, more or less, that the browser create a new
environment, add the all variables from the current scope, compile and
execute the script, collect garbage then export the variables back into
the original environment. It can't be cached for optimisation, and is
almost impossible to debug if errors occur.

A thread you may like to read:

<URL:http://groups.google.co.uk/group/comp.lang.javascript/browse_frm/thread/736d828ab27c3bb3/8e37f4c9436436ad?q=why+is+eval+evil&rnum=1&hl=en#8 e37f4c9436436ad>

And a blog:
<URL:http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx>
Google 'javascript eval is evil' for plenty more.
--
Rob
Nov 1 '05 #6
Zif
RobG wrote:
Stefan Mueller wrote:
Thanks a lot for your suggestions and solutions.

Today I tried a different approach:

1. Store the command to a string variable
xelement = document.createElement("input")
xelement.type = "button"
var tempeval = "xelement.onfocus = function() {FocusIsOn =
'Button_" + ButtonNumber + "'}"


xelement.id = 'B' + ButtonNumber;
xelement.onfocus = function (){
FocusIsOn = 'Button_' + this.id.replace(/B/,'');
};

Avoids eval and closure (and hence IE memory issues).


So does:

xelement.onfocus = new Function(
'FocusIsOn = "Button_' + i + '";'
);

[...]
--
Zif
Nov 1 '05 #7
Zif
RobG wrote:
Stefan Mueller wrote:
Thanks a lot for your suggestions and solutions.

Today I tried a different approach:

1. Store the command to a string variable
xelement = document.createElement("input")
xelement.type = "button"
var tempeval = "xelement.onfocus = function() {FocusIsOn =
'Button_" + ButtonNumber + "'}"


xelement.id = 'B' + ButtonNumber;
xelement.onfocus = function (){
FocusIsOn = 'Button_' + this.id.replace(/B/,'');
};

Avoids eval and closure (and hence IE memory issues).


So does:

xelement.onfocus = new Function(
'FocusIsOn = "Button_' + ButtonNumber + '";'
);

[...]
--
Zif
Nov 1 '05 #8
Wow, and I thought using 'eval' is a smart solution.
Thanks a lot for your explanation. So I know now not using 'eval' anymore.

I don't like to use the Id or name because than the onfocus statement is
still dynamic and the Id and name not always have to be the same as the
'FocusIsOn' has to be set to.

So I do now
xelement.onfocus = new Function('FocusIsOn = "Button_' + ButtonNumber +
'"');

But what do I do here? Do I really create for each onfocus a new function.
If yes, is that really better than 'eval'? Why is the 'F' in function a big
letter?
How does the stored onfocus statement look like? With 'eval' the statement
was static like I would it have hard coded
xelement.onfocus = function() {FocusIsOn = "Button_43"}

Stefan
Nov 1 '05 #9
Me again.
After further testing I figured out that the solution with
xelement.onfocus = new Function('FocusIsOn = "Button_' + ButtonNumber +
'"')
does not work if I have several events like
xelement.onfocus = new Function('FocusIsOn = "Button_' + ButtonNumber +
'"')
xelement.onmouseover = new Function('if (FocusIsOn = "Button_' +
ButtonNumber + '") {alert("message 1")})')
xelement.onmouseout = new Function('if (FocusIsOn = "Button_' +
ButtonNumber + '") {alert("message 1")})')

Therefore I use now Rob's solution which works perfect
xelement.onfocus = function() {FocusIsOn = this.id}
xelement.onmouseover = function() {if (FocusIsOn = this.id)
{alert("message 1")}}
xelement.onmouseout = function() {if (FocusIsOn = this.id) {alert("message
2")}}

Thanks again
Stefan
Nov 1 '05 #10

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

Similar topics

6
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
7
by: Donna Hawkins | last post by:
I want to use javascript to redirect to a URL which has been passed as a variable (in php). I have searched but cannot find any solution. I think this code is a basic redirect: <script...
4
by: mexican_equivalent | last post by:
X-no-archive: yes Newbie C++ programmer reads the following statement from the C++ 'Deitel & Deitel' textbook: "Reference variables can be used as local aliases within a function. They must...
3
by: markaelkins | last post by:
Hi. I am trying to enter a variable in the treenodesrc of a treenode. I am basically trying to send an ID variable into sql to return different records. I've searched everywhere and cannot find the...
4
by: Ya Ya | last post by:
Hi, I have a string with some fixed text and variable text. For example: "this is a fixed text THE NEEDED INFO more more fixed text". How do I get the the variable text (THE NEEDED INFO) from this...
2
by: timpera2501 | last post by:
I am a newb to OOP programming and I'm only just starting with C#. I've done a TON of reading lately, and I'm currently in the process of modifying some of the function provided by the...
24
by: garyusenet | last post by:
I'm working on a data file and can't find any common delimmiters in the file to indicate the end of one row of data and the start of the next. Rows are not on individual lines but run accross...
24
by: allpervasive | last post by:
hi all, this is reddy, a beginner to c lang,,here i have some problems in reading and modifying the contents of a file,, hope you can help to solve this problem. Here i attach the file to be...
9
by: LamSoft | last post by:
Class B { public B() {} } Class A : B { public static string ABC = "myABC"; public A() {} }
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...

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.