php - How do I change the value of a text field on click? -
i making calculator in php. 1 problem have been having trouble with, this.
<input type="button" name="insert" value="0" style="width: 30px; height: 35px" onclick="zerocheck()"> so having textfield containing "0", replace 0 instead of adding "0" onto that.
my textfield name called entry.
i tried develop function in order solve problem no avail.
function zerocheck(){ if (entry.value == '0'){ entry.value=='0'; } else{ return entry.value+='0'; } } this isn't doing @ all. doing wrong here?
if appreciated.
the simplest solution can think of is:
function zerocheck(el) { // caching value because it's used multiple times var v = el.value; /* setting value ternary/conditional operator: v == '0' : testing value equal given string if equal: value set to: '' + v (so there's no change), if not equal: value set to: '0' + v (so 0 prepended). */ el.value = ( v == '0' ? '' : '0' ) + v; } in linked demo above javascript used following 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)" /> to add (basic) error-handling:
function zerocheck(el) { // caching value, because we're using few times var v = el.value, // saving number (this way 1.4 , 1 both preserved) num = parsefloat(v); // basic check see value number // (or rather 'not not-a-number): if (!isnan(num)) { el.value = ( v == '0' ? '' : '0' ) + v; } else { // default handling here, handle non-numeric values: el.value = 0; } } because think mis-read question, i've updated answer possibility, handles sibling text-input elements , takes account values have leading-zero:
function zerocheck(el) { /* gets 'input' elements within same parentnode contains button that's clicked: */ var inputs = el.parentnode.getelementsbytagname('input'), /* declaring variables used in loop, they're not being re-declared through loop */ v, num; (var = 0, len = inputs.length; < len; i++) { v = inputs[i].value; num = parsefloat(v); // if input button, don't anything, keep going if (inputs[i] == el) { continue; // otherwise if number not not-a-number: } else if (!isnan(num)) { inputs[i].value = (v.charat(0) == '0' ? '' : '0') + v; } else { inputs[i].value = 0; // error-handling } } }
Comments
Post a Comment