HTML:
<input type="text" id="screen" />
<div id="keypad">
<button>7</button>
<button>8</button>
<button>9</button>
<br />
<button>4</button>
<button>5</button>
<button>6</button>
<br />
<button>1</button>
<button>2</button>
<button>3</button>
<br />
<button>0</button>
</div>
JavaScript:
window.onload = function () {
var screen = document.getElementById('screen'),
keypad = document.getElementById('keypad'),
buttons = keypad.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
screen.value = screen.value + this.innerHTML;
return false;
};
}
};
完全な例:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form onsubmit="javascript: /* Just for testing */ alert('Sending...'); return false;">
<input type="text" id="screen" />
<div id="keypad">
<button>7</button>
<button>8</button>
<button>9</button>
<br />
<button>4</button>
<button>5</button>
<button>6</button>
<br />
<button>1</button>
<button>2</button>
<button>3</button>
<br />
<button>0</button>
</div>
</form>
<script>
window.onload = function () {
var screen = document.getElementById('screen'),
keypad = document.getElementById('keypad'),
buttons = keypad.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
screen.value = screen.value + this.innerHTML;
// Try to comment line below to see what happens
return false;
};
}
};
</script>
</body>
</html>
デモ: JSFiddle