I have the script
<input type="text" name="name" value="Joe Bloggs" onfocus="this.value=''"/>
Just like I开发者_JAVA技巧 am doing with the onfocus="this.value…"
can I change the background of the field (+ change other things?)
Also, does anyone have a better idea of how to do the script above, but so that the text reappears when the deselect it?
It's considered best practice to leave styling to CSS and logic to JS.
You can do this in css using the :focus
pseudo-class. (http://www.quirksmode.org/css/focus.html) Unfortunately, it doesn't work in IE7 or lower. For those browsers, you can use javascript to add a class to the <input>
to do the same thing.
CSS
input:focus, input.focus {background:#ff0}
If you are using jQuery, here is how you would do that.
$('input').focus(function(){
$(this).addClass('focus');
});
$('input').blur(function(){
$(this).removeClass('focus');
});
Something along the lines of
onfocus="this.value=''; this.style.backgroundColor='#f00'" onblur="this.style.backgroundColor='white'"
will get approximately what you want done simply, although it would also be possible for it to interact badly with presentation defined elsewhere and as such is probably rather crude to be considered a best practise.
Alternatively, you could as suggested add / remove a specific class to the element onfocus / onblur. At this point I would also second the jQuery recommendation: although it's hardly necessary just for this, you will find that it makes life with Javascript in general much more pleasant.
If you use jQuery, something like
$('input').focus(function() { $(this).addClass('focus') });
$('input').blur(function() { $(this).removeClass('focus') });
would allow you to cleanly define the appearance of focussed inputs in CSS. Consult jQuery documentation for the surrounding context necessary to make this work.
...id="name" onfocus = "javascript:yourFunction();"...
Then, your js looks something like this:
var inputFld = document.getElementById('name');<br/>
var oldval = inputFld.value;<br/>
var tempval = "";<br/>
function yourFunction(){
inputFld.value = tempval;<br/>
inputFld.className = "test" //(building from the first answer)<br/>
//do other stuff...<br/>
}
Then, you can also add an onblur="javascript:anotherFunction();" where anotherFunction() resets inputFld.value to the original value.
Note, best practices advise you should avoid those global vars and that you attach event listeners for the onblur and onfocus events rather than inlining them. But, at least, initially, you can see if this code as it is written works for you...
On your event, append the class name...
el.className+= 'test'
then set a background on that class in your css.
精彩评论