I have a sample code:
<input width="50" type="text" value="" name="application_id" id="text_input">
<a href="#" onclick="addSelect('1', 'Test Name');" title="Click to add this item">Test Name</a>
And javascript
function addSelect(id, title) {
document.getElementById('text_input').value = title;
}
When I run code, result error is addSelect is not defined
? demo here , how to fit it ?
I have a sample code:
<input width="50" type="text" value="" name="application_id" id="text_input">
<a href="#" onclick="addSelect('1', 'Test Name');" title="Click to add this item">Test Name</a>
And javascript
function addSelect(id, title) {
document.getElementById('text_input').value = title;
}
When I run code, result error is addSelect is not defined
? demo here , how to fit it ?
- jsfiddle/TmLut/2 – Nemoden Commented Nov 27, 2012 at 6:55
- @Nemoden same as you work fine for me if I changed it to no wrap(body) – Anirudha Gupta Commented Nov 27, 2012 at 6:56
-
1
And please change to
onclick="return addSelect....
and addreturn false;
to the end of your function jsfiddle/CcdNf/1 - I also changed to plain JS from mootools – mplungjan Commented Nov 27, 2012 at 7:05
2 Answers
Reset to default 5Your script has been defined to run onLoad
, which means your function is not available in the global scope like you expect. It will be defined in a local scope of some onLoad
method (whichever jsFiddle uses). With this setting, I think jsFiddle puts your code into this or something similar to:
window.onload = function () {
// Your code
};
(which is similar to onDomReady
option)
This is so you don't have to worry about binding the right event and you can just test your script (making sure the page has loaded).
When you try to call the function, which you expect to be in the global scope, it won't work. Just change the setting on the left to no wrap (head)
(or no wrap (body)
)
http://jsfiddle/TmLut/3/
And as mplungjan has pointed out, and I somehow didn't realize at all, when using the onclick
of the anchor element, you'd probably want to prevent default behavior of the link (even if it's just to go to "#"), and can be achieved in several ways, but one is:
<a href="#" onclick="runFunction();return false;">Text</a>
Although at the same time, one might argue you shouldn't have inline handlers at all, and would want to be binding the event with Javascript pletely. Depending on that case, you have options to prevent the default behavior still. In any case, you can still grab ahold of the event
object (normalized per browsers...which jQuery does, by the way) and call event.preventDefault();
in the method.
Here its http://jsfiddle/TmLut/4/
I changed onload
to head
on the left side select box
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745158462a4614266.html
评论列表(0条)