How to Change Input Text With Javascript


Many web developers use JavaScript to change a user's text input after he types it into a text box. For example, you could use JavaScript to remove objectionable words from a forum user's post. You could also display a personal greeting to a site visitor after she enters her name on sign-up forms. After learning a few JavaScript commands, you can manipulate input text and format it to suit your needs. These commands are generic and work across all browsers.

Things You'll Need

  • HTML Editor or Notepad
  • Create a new HTML document.

  • Add this code to the body section of the document:

    <h2 id=\"myHeading\"></h2> <p />
    <input id=\"myTextbox\" type=\"text\" /><p />

    This creates an empty heading and a text box element. You will enter a name into the text box. IDs are optional, but you must use them if you plan to manipulate the contents of an HTML element using JavaScript.

  • Add this button element below the text box declaration:

    <input id=\"changeText\" type=\"button\" value=\"Click to change heading text\" onclick=\"return changeText()\" />

    When you click the button, JavaScript will change the text that you entered and display the new text in the heading and the text box.

  • Add this JavaScript function to the script section of the document:

    function changeText() {
    var headingObject = document.getElementById('myHeading')
    var textboxObject = document.getElementById('myTextbox')
    var originalText = textboxObject.value
    textboxObject.value = \"Hello \" + originalText
    headingObject.innerHTML = \"Text changed to -> Hello \" + originalText

    The \"document.getElementById\" command retrieves an HTML element and makes it available to JavaScript. In this example, the two \"document.getElementById commands retrieve the heading element (myHeading) and the text box element (myTextbox). The function then gets the text from the text box and adds \"Hello\" to the string. Finally, the \"innerHTML\" properties of the heading and text box elements are changed.

  • Open the document in a browser, enter a name in the text box and click the button. The JavaScript function will add \"Hello\" to the name and update the contents of the two HTML elements.

Tips & Warnings

  • Use the \"innerHTML\" to retrieve and update the text of any HTML element. For example, you could change a button's text from \"Click to submit\" to \"Thank you for purchasing XYZ\" after a site visitor entered a product name. The \"outerHTML\" property allows you to alter the text and the style of input text.

Related Searches


  • Photo Credit typing girl image by Andrey Kiselev from
Promoted By Zergnet



You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!