私が考えることができる最も簡単な解決策は次のとおりです。
function zeroCheck(el) {
// caching the value because it's used multiple times
var v = el.value;
/* setting the value with a ternary/conditional operator:
v == '0' : testing that the value is equal to the given string
if it is equal: the value is set to: '' + v (so there's no change),
if it is not equal: the value is set to: '0' + v (so a zero is prepended).
*/
el.value = ( v == '0' ? '' : '0' ) + v;
}
JS フィドルのデモ。
リンクされたデモでは、上記の JavaScript が次の HTML と共に使用されます。
<input type="button" name="insert" value="0" onClick="zeroCheck(this)" />
<input type="button" name="insert" value="1" onClick="zeroCheck(this)" />
<input type="button" name="insert" value="2" onClick="zeroCheck(this)" />
<input type="button" name="insert" value="3" onClick="zeroCheck(this)" />
(基本的な) エラー処理を追加するには:
function zeroCheck(el) {
// caching the value, because we're using it a few times
var v = el.value,
// saving the number (this way 1.4 and 1 are both preserved)
num = parseFloat(v);
// a basic check to see that the value is a number
// (or rather that it is 'not Not-a-Number):
if (!isNaN(num)) {
el.value = ( v == '0' ? '' : '0' ) + v;
}
else {
// default handling here, to handle non-numeric values:
el.value = 0;
}
}
JS フィドルのデモ。
質問を読み間違えたと思うので、この回答を別の可能性で更新しました。これは、兄弟のテキスト入力要素を処理し、すでに先行ゼロを持つ値も考慮に入れます。
function zeroCheck(el) {
/* gets all the 'input' elements within the same parentNode that
contains the button that's to be clicked: */
var inputs = el.parentNode.getElementsByTagName('input'),
/* declaring the variables to be used in the loop, so they're not
being constantly re-declared through the loop */
v, num;
for (var i = 0, len = inputs.length; i < len; i++) {
v = inputs[i].value;
num = parseFloat(v);
// if the input is the button, don't do anything, just keep going
if (inputs[i] == el) {
continue;
// otherwise if the number is not Not-a-Number:
} else if (!isNaN(num)) {
inputs[i].value = (v.charAt(0) == '0' ? '' : '0') + v;
} else {
inputs[i].value = 0; // error-handling
}
}
}
JS フィドルのデモ。