简体   繁体   中英

JS event handling, stuck on the basics

I can no longer use inline scripting due to a change by a webhost, so I'm migrating a few scripts to external files. I can't seem to get this one to fire:

Purpose of script: applies rot13() to form data before sending to server, by hovering over submit button

rot13.js

   function rot13(s) {
     return s.replace(/[A-Z]/gi, c =>
       "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"[
       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
   }
   
   function assignRots()
   {
      var new_auth = document.getElementById("author").innerHTML;
      document.getElementById("author").innerHTML = rot13(new_auth);
      
      var new_email = document.getElementById("email").innerHTML;
      document.getElementById("email").innerHTML = rot13(new_email);
      
      var new_msg = document.getElementById("msg").innerHTML;
      document.getElementById("msg").innerHTML = rot13(new_msg);
   }
   
   document.getElementById("submit").onmouseover = assignRots();

form.html

   <form id="newCommentForm" method="post" action="" enctype="multipart/form-data">

   <input name="author" id="author" type="text" value="" size="30" maxlength="50" />
   
   <input name="email" id="email" type="text" value="" size="35" maxlength="50" />
   
   <textarea name="msg" id="msg" rows="12" cols="80" maxlength="4000"></textarea>
   
   <input type="submit" id="submit" name="submit" value="Submit">

   </form>

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

You should not use innerHTML with form inputs . You must use .value property instead. Try the below code:) Also with the mouseover event simply use assignRots not assignRots() .

function assignRots()
   {
      var new_auth = document.getElementById("author").value;
      document.getElementById("author").value= rot13(new_auth);
      
      var new_email = document.getElementById("email").value;
      document.getElementById("email").value= rot13(new_email);
      
      var new_msg = document.getElementById("msg").value;
      document.getElementById("msg").value= rot13(new_msg);
   }

document.getElementById("submit").addEventListener("mouseover",assignRots); 

onmouseover expects a function, instead you are assigning it to the return value of your function.

try:

document.getElementById("submit").onmouseover = assignRots;

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