简体   繁体   中英

Javascript form innerHTML

i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.

here goes my code :

<script type="text/javascript">

     function clearTextField(){
         document.getElementsById("commentText").value = "";
     };

     function sendComment(){
         var commentaire = document.getElementById("commentText").value;
         var htmlPresent = document.getElementById("posted");

         htmlPresent.innerHTML = commentaire;
         clearTextField();
     };
</script>

and my HTML code goes like this:

<!doctype html>
<html>
 <head></head>
  <body>

   <p id="posted"> 
   Text to replaced when user click Send a comment button
   </p>

   <form>

  <textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea> 
  <button id="send" onclick="sendComment()">Send a comment</button> 

   </form>
  </body>
 </html>

So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.

Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.

I have tried three different broswer, I also have tried with getElementByTagName(); method without success.

Do I miss something ? My code seems legit and clean, but something is escaping my grasp.

What I wanted out of this code is to replace HTML code between a given markup (like <p> ) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.

Any help would be appreciated.

EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .

There is no document.getElementsById , however there is a document.getElementById . This is probably the source of your problem.

I don't think there is any document.getElementsById function. It should be document.getElementById .

"To set or get the text value of input or textarea elements, use the .val() method."

Check out the jquery site... http://api.jquery.com/val/

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