javascriptdom-eventsunobtrusive-javascript

How to read input from text on button click unobtrusively in Javascript?


How to read input from text on button click unobtrusively in Javascript? Can anyone provide a sample?

<script type="text/javascript>
window.onload = function() {

var btn = document.getElementById(
    "btn"
);
btn.addEventListener("click",function() { alert("bar"); },false);

}
</script>    

and in the body:

<div id="content">
<input type="text" id="percent" value="" />
<button id="btn">click</button></div>

Solution

  • Yes, addEventListener (with IE's attachEvent) is the most unobtrusive. To get the value of the textbox you simply use the .value property of the textbox.

    <script type="text/javascript">
        window.onload = function () {
            var btn = document.getElementById("btn");
            if (btn.addEventListener) {
                btn.addEventListener("click", btnClick, false);
            } else if (btn.attachEvent) {
                btn.attachEvent("onclick", btnClick);
            }
        };
        function btnClick() {
            alert(document.getElementById("percent").value);
        }
    </script>