I have a inline function that works fine. When the link is clicked it puts the text into the textField:
<a href="#" onclick="document.getElementById('textField').value =(this.text);">someText</a>
What i want to do is be able to call the above as a function instead of writing it inline. Example:
function setValue() {
document.getElementById('dd').value =(this.text);
}
and be able to call it like so:
<a href="#" onclick="setValue();">someText</a>
I thought it would be simple but for some reason it is not work and giving me error in firebug. I think it has something to do with "this.text" being called from a function instead of inline. Thanks for any help.
I have a inline function that works fine. When the link is clicked it puts the text into the textField:
<a href="#" onclick="document.getElementById('textField').value =(this.text);">someText</a>
What i want to do is be able to call the above as a function instead of writing it inline. Example:
function setValue() {
document.getElementById('dd').value =(this.text);
}
and be able to call it like so:
<a href="#" onclick="setValue();">someText</a>
I thought it would be simple but for some reason it is not work and giving me error in firebug. I think it has something to do with "this.text" being called from a function instead of inline. Thanks for any help.
Share Improve this question asked Dec 27, 2011 at 0:01 user982853user982853 2,45015 gold badges59 silver badges85 bronze badges 1- Well, what does the error say? You seem to not know this but errors actually provide useful information about themselves (a message and the line number). – Šime Vidas Commented Dec 27, 2011 at 0:49
4 Answers
Reset to default 2Why not take it one step further and put the event binding code outside of the markup too? Separating your behavior from presentation is a good idea.
$("#anchor_selector").click(function () {
$("#dd").val(this.text);
});
I would apply an id
attribute to your anchor and use it in the selector. Or you can use one of the many other selectors out there to target your link.
function setValue( text ) {
jQuery('#dd').val( text );
}
<a href="#" onclick="setValue( jQuery( this ).text() );">someText</a>
You need to pass the context, otherwise this
will be the global scope (window):
<a href="#" onclick="setValue(this);">someText</a>
function setValue(context) {
document.getElementById('dd').value = $(context).text();
}
The this
is being lost. Try setting setValue()
to take a reference to the element as the first param, and then pass this
in the handler.