In languages such as Java or GUI frameworks such as Qt for C++, it is possible to get a handle to some block of text (e.g. a label widget) the user cannot change, but which the program can modify based upon some condition being satisfied. I’d like to be able to do the same thing on an HTML web page from within some JavaScript code.
For example, consider a web page for entering user credentials. If the credentials are invalid, I’d like to display a message on the current web page without having to load a completely new page.
I’ve gotten it to work using an HTML text box or textarea, set to disabled, read only with some display style changes (via CSS). Changes induce some JavScript code to run which may result in changes to the value field of these text boxes or textareas. While this works okay, it just doesn’t seem right. Is there a more orthodox way of accomplishing this?
Sure. There are a few libraries to handle this.
You may be asking for form validation. If so, try jQuery and jQuery’s validate extension library: demo
Or you may be asking for a more generic-use observer pattern. If so, try one of the many MVVM/MVC libraries for JavaScript such as backbone.js or knockout.js (also ember, agility, angular, and spine): jsfiddle
edit: also note that if your need is just standard form validation, you can accomplish it in jQuery validate without any code to speak of – just add properties directly on the HTML elements themselves indicating what the validation rules are. Unfortunately, HTML5 data attributes weren’t around when it was written, so you apply the validation rules as CSS classes.
edit 2: also note that jQuery validate out-of-the-box supports remote validation, such as the credentials or username-already-exists scenario: demo or documentation