Search code examples
javascripthtmldecoupling

Proper way to retrive HTML textbox data using JavaScript


Assuming I have a simple HTML page like the following:

<html>
  <head>...</head>

  <body>
    <input type="text" id="mytextarea" />
    <input type="button" id="button1" onClick="..." />
    <input type="button" id="button2" onClick="..." />
  </body>
</html>

What is the best way to access the text in the text-field with id="mytextarea" in a JavaScript function, without creating code heavily coupled to the HTML page, given the knowledge that button1 and button2 cause different manipulations on the text?


Just as an example, assume I am expecting a binary number in the text field, and button1 will convert it to an integer decimal number, but button two will convert it to a fractional decimal number. How can I handle this without tightly coupling the JavaScript code to the HTML page? Is there some way to send the data in mytextarea down to the JavaScript code, without having to use a document.getElementById('mytextarea') in the JavaScript functions themselves?


Perhaps I should clarify,

I am not looking for an alternative to using getElementById, I am looking for a way to write JavaScript code that can use a text-field in an HTML page without being coupled to it. In other words, I would like to know how to write JavaScript functions and HTML pages in such a way that (1) the JavaScript functions can perform work on data in the HTML page and (2) the JavaScript function can be be moved to another HTML page and used there, without changing said function.


Solution

  • I think this is what you want:

    First you create an object called Textarea that lets you pass a textarea element as an argument:

    function Textarea(textarea) {
        this.container = textarea;
        this.value = textarea.value
    };
    

    Then you can add methods shared by every instance of the Textarea object:

    Textarea.prototype.ChangeValue = function(){
        console.log( 'Please add your ' + this.value );
    };
    

    In this way, you can pass mytextarea and modify it as you want. This allows to reuse properties and methods in your object in other textareas or other projects where you need it.

    t = new Textarea(document.getElementById('mytextarea'));
    t.ChangeValue();
    

    Demo: http://jsfiddle.net/SQ2EC/