I'm having a weird problem with some JavaScript/DOM code I've been playing with. I'm trying to assign the .onKeyUp and .onChange events/methods to a text input like so:
form.elements["article"].onkeyup = "alert('test');";
Oddly, assigning using that method is doing nothing, and I'm forced to do this manually using:
form.elements["article"].setAttribute("onkeyup", "alert('test');");
Am I missing something here? I've used the first method I mentioned before and it has worked fine.
Try this:
form.elements["article"].onkeyup = function() { alert("test"); };
Steve
You need to assign a function, not a string. For example:
form.elements["article"].onkeyup = function(){alert('test');};
The only things I know that will take a string and eval it (other than eval) are setTimeout and setInterval.
Related
i have this Javascript function
function webit(thumb){
webi = document.createElement("img");
webi.alt=thumb.id.replace("t", "");
webi.id = "w"+webi.alt;
webi.className = "web";
webi.src= thumb.src.replace("thm","web");
webi.height=233;
webi.onclick='alert()';
document.body.appendChild(webi);
}
which is supposed to embed a larger version of a thumbnail image the end of the document. It works fine except that any javascript function ( ie onXXX) stays resolutely null. This seems to be no matter which JS function i use and afaict any thing i try to set it to.
The above example uses
webi.onclick='alert()';
which fails leaving onclick null, though all the other statements succeed.
When in javascript the .onclick property expects a function not a string
webi.onclick=function(){ alert(); };
You could also use the addEventListener method to set an event handler
webi.addEventListener("click",function(){ alert(); });
There are two problems, you are giving quotes to alert & onclick requires a function that can be called after clicking on it, you should not call the assigned function.
webi.onclick=function(){alert()};
You might consider declaring webi as var. Without "var", you implicitly defined window.webi, and it will introduce memory leaks.
var webi = document.createElement("img");
In addition, jQuery is usually a better choice than raw js/browser API.
I have a global variable var num_tab=1;, a function that creates a link a href :
function Addsomething()
{
$("#tout").html("<a style=\""+"margin-left:-20px;"+"\" onClick=\"eval(num_tab=2)\" href=\""+"#tab1"+"\" data-toggle=\""+"tab"+"\">SELECT</a>");
Bla,Bla..
$("#champ1").append('<li id=\"1\" class="champ" onclick="insertAtCaret("sousTab'+num_tab+'");" value=\"1\">1</li>');
}
What i want to do is to create a href that when clicked changes the value of the variable num_tab, but if you can see the href is inside a jquery html(), which makes me confused about how to assign a value to the variable. I almost tried everything: onClick=\"num_tab=2\",onClick=\""+num_tab+"=2\"
Actually i tried something: when i write onclick='num_tab=2;alert("+num_tab+");' i still get the initial value of num_tab, seems it's more like a problem of local and global variable and i can't figure out it yet.
Please don't use eval(). It's insecure and not the appropriate tool for this job. Just assign a function to the onclick:
$("#tout").html("<a onclick='set_num_tab(2)'">); //fill out the rest of this line
function set_num_tab(value) {
num_tab = value;
}
That should give you an idea of how to do it. btw there's no reason you can't use single quotes around an onclick like that.
Alternately, this would work:
$("#tout").html("<a onclick='num_tab=2'">);
But that's pretty messy. I try to avoid inline JavaScript.
I have written this code (this is a snippet) that doesn't seem to be working. I have isolated it to here.
grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]
Is it possible to create references to native function in javascript. I am doing something with the grabbed element, I just left it out for example. The grab function doesn't seem to work.
I am using FireFox's most recent version
The way you're doing it will mess up the assignment of the this value for the function.
grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]
here this will be the global object. Try:
grab.apply(window.document, ["blueBox"])
or in newer browsers:
grab = window.document.getElementById.bind(window.document);
to get directly define what this will be.
The first step here is always the JavaScript console. Firebug is your friend. Tell us the error message if it doesn't mean anything to you.
In the mean time, here is a workaround:
var grab = function(id) { return window.document.getElementById(id); }
function grab(id) {
return window.document.getElementById(id);
}
grab("blueBox");
The reason is because the function getElementById is not being called as a method of document, so its this keyword doesn't reference the right object. Using call as suggested in other answers shows that when this references the document, getElementById works.
I have javascript function sample('textValue') and have to call at server side on anchor click. I tried below code
string text="xyz";
anchor.Attributes.Add("onclick","javascript:sample('"+text+"');
but the value of the text is not assigning correctly. Encoded string gets added. The result in view source looks like
javascript:sample('xyz')
But i need javascript:sample('xyz')
What server/backend language do you use? PHP? Do you use any framework (Zend, CakePHP...)?
On the JS side do something like this:
Option 1
Test
Option 2
Test
<script type="text/javascript">
document.getElementById('clicky-clack-link').onClick = function() {
sample('test');
};
</script>
Note: Also check out jQuery if you haven't.
I wonder if you could just do this:
string text="xyz";
anchor.Attributes.Add("onclick", function(){ sample(text); } );
What does it do? Well, the onclick handler takes a function with no arguments, right? That is, what to do if somebody clicks the link. If you're coding this by hand in HTML, you can use the javascript:a_statement_goes_here to describe the code to run. I expect the browser will just create a function out of that. Since you're assigning this in JavaScript, you have to do that yourself (unless you write out to the document - that might work) and assign the function. But you don't have such a function yet - you have one sample that takes an argument - hence the anonymous function closing the text argument.
This is based on the assumption, that the above is actually client-side code. I'd be very surprised, if JS didn't allow you to assign a function to an attribute. In fact, I think the problem you are running into, is JavaScript trying to be very smart and make sure assigning a string, will stay a string - that is why your ' got encoded.
Have a go, tell me how it went. Ta!
I am trying to change the value of the onblur attribute of a text input after the page has finished loading.
When I do the following, it simply fires the function:
ip.onblur = stopCalcUpInt(this,10);
When I do the following, I have success:
ip.onblur = function onblur(event){stopCalcUpInt(this,10);}
Unfortunately, the whole point of this is to be able to dynamically set the second parameter for stopCalcUpInt(). If I hard code a value for it... it works fine... but any attempts to pass varibles to this fails... instead of putting the value of the variable as the second param it just puts the plain text of the variable name itself. Here is ideally what I am TRYING to do:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
In this example, when I alert the ip.onblur I get:
It depends what this is intended to refer to. In an event handler this refers to the element on which the event is being handled. If that's what you want then your code looks good as written; this will point to ip.
If you intend this to refer to the this from outside the event handler and not ip then try this:
var self = this;
ip.onblur = function(event) { stopCalcUpInt(self, self.value); };
The answer to getting this to work was super easy, yet not overly obvious. Instead of:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
I did this:
ip.setAttribute('onblur','stopCalcUpInt(this,\'' + ip.value + '\');');
Works perfectly... no more banging my head against the wall! Yay!
ip.onblur = function() {stopCalcUpInt(this,this.value);}
ip.onblur is an event handler... i.e. it's a function
Now, when you alert a function, FF will show you the source code for that function (if it's user defined).
That is why you're seeing the plain text of the variable name.
For an event handler, this is the element that is currently handling the event. So, if you're setting the onblur handler of an input box, you will have access to the contents of that input box.
The code sample that you provided:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value);}
should work correctly. Try
ip.onblur = function onblur(event){alert(this.value); stopCalcUpInt(this,this.value);}
if you want to be sure
Is stopCalcUpInt expecting a number in the second parameter? The value attribute will return a String, while in your hardcoded example you're passing a number type. Try this:
ip.onblur = function onblur(event){stopCalcUpInt(this,this.value * 1);}
As explained in QuirksMode:
Since multiplying assumes numbers,
JavaScript makes the string a number,
if possible.