简体   繁体   中英

Replace word user wrote in Text Box with JavaScript

So I'm typing my first useful code for school right now, (I have about 1-2 years of basic coding knowledge) I know HTML and CSS, but right now I'm getting into JavaScript. I was wondering how by the press of a button, a word a user wrote in an HTML text box replaces with another word. Let's say they wrote: "I like eating pie." In an HTML textarea element. How can I use JavaScript so I can replace the word "like" with "love" by the click of a button? Sorry if I'm bad at explaining, questions are welcomed!

You will have to add the id attribute to textbox in form. like:

<form>
 <input type="Text" id = "textField">
 <input type = "Button" Value = "Change Text" onclick="ChangeText()">
</form>

The javaScript function(ChangeText) should have a statement:

document.getElementById('textField').Value= "I love eating pie.";

You can also use document.getElementByName().

If you want to change a single word then you can add following in ChangeText() function:

var oldtext = document.getElementById('textField').Value;
var newtext = oldText.Replace("like","love");
document.getElementById('textField').Value= newText;

So I wrote some code that does exactly what you asked for. The code is pretty simple it uses "onclick" to call a function that gets the value of the textarea replace the words (using the "replace" function of javascript) and then changes the value of the textarea with the new value (with the replaced words)

<!DOCTYPE html>
<html>
  <head>
    <script>
      function replace(){
        var text = document.getElementById("textarea").value;
        var newText = text.replace("like", "love");
        document.getElementById("textarea").value = newText;
      }
    </script>
  </head>
  <body>
    <textarea rows="4" cols="50" id="textarea"></textarea>
    <button id="button" onclick="replace();">replace</button>
  </body>
</html>

Hope it help. Anything you can ask.

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