Log in

View Full Version : Can you determine the field that the cursor is in using javascript?



tbroas
07-17-2006, 03:31 PM
Hi,

I'm new to JavaScript, but I am trying to write a script that adds text to the fields of a form whan a button is clicked:

------------------------------------------------------------------------
<script language="javascript" type="text/javascript">
function addStuff() {
var newtext ='New Stuff';
document.create.title.value += newtext;
}
</script>


<FORM NAME="create">
Enter the course title:<BR><INPUT TYPE=TEXT SIZE=66 NAME="title">
</FORM>
<input type="button" value="Add Text" onClick="addStuff();">
--------------------------------------------------------------------------

The code works, and when I click on my button, "New Stuff" appears in the text area named "title". Here is my problem. I want to have multiple fields on the form along with text areas, but I only want to have one button that works for all the fields. They way my code is written now, I would need a function for every field since I use document.create.title.value +=newtext;

Is there a way I can determine name of the field that the cursor is currently in using something like onFocus and pass it to the function as a variable so that it will work on any field?

Thanks in advance for any advice. :)

Twey
07-17-2006, 04:34 PM
window.focussedFormElement = null;

function addStuff() {
var newtext = 'New Stuff';
window.focussedFormElement.value += newtext;
}

window.onload = function() {
var n = function() {
window.focussedFormElement = this.form.focussedElement = this;
}, p = function() {
window.focussedFormElement = this.form.focussedElement = null;
};
for(var i = 0, f = document.forms; i < f.length; ++i) {
f[i].focussedElement = null;
for(var j = 0, e = f[i].elements; j < e.length; ++j) {
e[j].onfocus = n;
e[j].onblur = p;
}
}
};Notes on your original code:
Forms needn't always be collected as properties of the document element, and elements needn't always be collected as properties of their forms. You should use the document.forms and form.elements collections instead (for example, rather than document.create.title.value, you should use document.forms.create.elements.title.value). However, it's a much better and more flexible idea to pass the form or element to the function as a parameter, rather than hard-coding it into the function. That way, if you change the name of the form or its elements, the function still works.