简体   繁体   中英

Accessing a text area within a form using

Please could you advise on the following:

I have a registration form, and within that a text area

<form id="register" name="register" method="post" action="register.php">

<textarea rows="5" id="bio" name="bio" method="post">Biographical information</textarea>

</form>

Using java script i have been trying to create an event handler for the onfocus and onblur events so the default text is removed on focus and restored on blur, as follows:

var bioField = document.getElementById("bio");

bioField.onfocus = function() {
    if (bioField.value == "Biographical information") {
        bioField.value = "";
    }
};

bioField.onblur = function() {
    if (bioField.value == "") {
        bioField.value = "Biographical information";
    }
};

i thought by getting the element by id would work, but it doesn't seem to be. no other duplication of names/id exist.

Any help much appreciated. Thanks guys

使用占位符属性:

<textarea rows="5" id="bio" name="bio" method="post" placeholder="Biographical information"></textarea>

It's working fine, perhaps the issue is that the placeholder default is "Biographical Information" and the script is testing for "All about you". The change that you made as I was posting this is exactly what you needed.

var bioField = document.getElementById("bio");

bioField.onfocus = function() {
    if (bioField.value == "Biographical information") {
        bioField.value = "";
    }
};

bioField.onblur = function() {
    if (bioField.value == "") {
        bioField.value = "Biographical information";
    }
};

http://jsfiddle.net/YeaTQ/1/

My educated guess is that you've placed your code as is right into a <script> tag inside <head> so when the script runs the form has not loaded yet.

Move your <script> below the form or wrap everything with window.onload :

window.onload = function(){
   // Code goes here
};

You have two solutions:

  1. In order to not use the javascript code you wrote, Use the following code:

    <textarea cols="30" rows="5" id="bio" name="bio" onfocus="this.value = '' " onblur="this.value = 'All about you'">Biographical information</textarea>

  2. I think the javascript code is located before control (in the header I guess), Because of this, the onfocus and onblur properties are not initialized. You'll have to put the script at the end of the document (before the tag).
    Also, you script is searching for another text ("All about you") and not the current text that's inside ("Biographical information"). Even if you insert the javascript code at the of the document, the code it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM