1

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 ?

3
  • jsfiddle.net/TmLut/2 Commented Nov 27, 2012 at 6:55
  • @Nemoden same as you work fine for me if I changed it to no wrap(body) Commented Nov 27, 2012 at 6:56
  • 1
    And please change to onclick="return addSelect.... and add return false; to the end of your function jsfiddle.net/CcdNf/1 - I also changed to plain JS from mootools Commented Nov 27, 2012 at 7:05

2 Answers 2

5

Your 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.net/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 completely. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

When is the addSelect name lookup actually performed?
@Kos On the link click? What do you mean?
0

Here its http://jsfiddle.net/TmLut/4/

I changed onload to head on the left side select box

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.