简体   繁体   中英

Onblur,Onfocus javascript for TextMode=“MultiLine” not working

I've got a multiline asp.textbox input control.

I don't know if my issue is with ASP.NET, the Multiline control, or something else, but the onblur and onfocus are not working.

<script type="text/javascript">
  var defaultMsg = 'Write your message here or or call my voice at (xxx) xxx-xxxx.';
  var controlMsg = doc.createElement("input");
  controlMsg.id = "txtMessage";
  controlMsg.type = "text";
  controlMsg.value = defaultMsg;
  controlMsg.onfocus=function jpFocus() { if (this.value == defaultMsg) this.value = ''; }
  controlMsg.onblur=function jpBlur() { if (this.value == '') this.value = defaultMsg; }
</script>

And later....

<asp:TextBox ID="txtMessage" Columns="30" Rows="6" runat="Server" TextMode="MultiLine" />

Does anyone see a reason why this should not be working?

Actually, you're creating a html element and you are attaching an event to it. In addition, ASP.NET controls does not use the server side id. Here's what you should do :

var controlMsg = document.getElementById('<%= txtMessage.ClientID %>');
controlMsg.onfocus = // Some Code ...
controlMsg.onblur = // Some Code ...

Try using an anonymous function, like this:

controlMsg.onfocus=function() { if ( ...

Functions and function scope - MDN .

Also, you did call something like document.body.appendChild(controlMsg); , didn't you?

EDIT:

You are using doc.createElement . Make sure that doc definitely points to document .

Also, look at the page in Firefox and see if there are any errors or warnings in the Error Console.

Not sure which version your are using.Please Try this:

protected void Page_Load(object sender, EventArgs e)  
 {
   txtMessage. Attributes["onfocus"]="JavascriptMethod";  
 }

I'm not sure why this worked and other techniques did not, but this got my HTML to work:

    <textarea name="txtMsg" rows="6" cols="30"
      onfocus="if(this.value==this.defaultValue)this.value='';" 
      onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>

The text can be very long, and the control does not seem to care. Also, the text is only written in a single location.

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