简体   繁体   中英

Why textarea's .focus() and .blur() don't work

I have a textarea element in my form as follow.

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<form id="advertiseForm" name="advertiseForm"   method="post" >
<textarea rows="20" cols="70" name="textarea" id="textarea">Please enter additional information here...</textarea>

</form>
<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script>

</body>

Then I put .focus and .blur into a javascript file as

advertisementlandedvalidationatclient.js

$("#textarea")
  .focus(function() {
        if (txt == null) return;
        if (txt.value == "Please enter additional information here...") txt.value = '';

  })
  .blur(function() {
        if (txt == null) return;
        if (txt.value == '') txt.value = "Please enter additional information here...";

});

When I click or remove the mouse from textarea, "Please enter additional information here..." doesn't toggle (appear/disappear).

I tried another approach in this link It works, that approach needs the function SetMsg needs to be on top of the textarea . I don't like that approach because I want to separate HTML and Javascript codes into separate files and because of some other elements I need

<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script> below the form.

Why it doesn't work in the first .focus/.blur method and what could be the best approach? Thanks

You can use placholder attribute for the input elements

<textarea rows="20" cols="70" name="textarea" id="textarea" placeholder="Please enter additional information here..."></textarea>

If you really want this to do this with jQuery, you may fix the code as..

$("#textarea")
.focus(function() {
    if ($("#textarea").val() == null) return;
    if ($("#textarea").val() == "Please enter additional information here...") $("#textarea").val('');
})
.blur(function() {
    if ($("#textarea").val() == null) return;
    if ($("#textarea").val() == '') $("#textarea").val('Please enter additional information here...');
});

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