Tuesday, February 8, 2011

Javascript numeric input

This is my cheatsheet while playing with the javascript, always forgot about them so I job it down here

Easy to find, one of them is in here
http://javascript.internet.com/forms/validate-numeric-only.html

Round a number into 2 decimal place
var result = Math.round(annualPremium*100)/100



Convert string to Integer
http://www.keyboardface.com/archives/2006/04/04/javascript-string-to-int/
parseInt(10.10) //Return 10



Another alternative for number format
http://www.pageresource.com/jscript/j_a_03.htm
profits.toFixed(2) //returns 2489.82
profits.toPrecision(4) //returns 123.5 (round up)



Check is numeric
http://andrewpeace.com/javascript-is-numeric.html AND http://bytes.com/topic/javascript/answers/526119-convert-double-cdbl-javascript
valueCredit = document.getElementById('thisIsSparrta').value;
if( valueCredit != '' && !isNaN(valueCredit)){
    totalCredit += parseFloat(valueCredit);
}



Adding and removing 'readonly' attribute to element
http://bytes.com/topic/javascript/answers/655784-change-textbox-readonly
document.getElementById('helloworld').setAttribute('readonly', true);
document.getElementById('helloworld').removeAttribute('readonly');


Change the element background
http://www.codeproject.com/KB/scripting/focusBGColor.aspx
document.getElementById('helloworld').style.backgroundColor = '#EBEBE4';


Select all the text in textbox
http://javascript-array.com/scripts/onclick_select_all_text_in_field/
document.getElementById(id).focus();
document.getElementById(id).select();

p/s: Remember not to use 'onclick' function because just in case the user dont want to select all (they made typo mistake and want to remove only 1 character)


Check the element has what attribute
There is a source, but I forget whare I take it from
document.getElementById.hasAttribute('acinput')

p/s: The attribute can be anything actually, typically is 'readonly' for textbox

No comments: