Edit box number input restriction / auto-insert commas

// Client Side JavaScript function

function inputNumber(thisEvent, showComma, minDigits, maxDigits) {
	var minDigits = minDigits ? minDigits : 0;
	var maxDigits = maxDigits ? maxDigits : 100;
	
	// skip for arrow keys, tab key, and shift+tab
	var code = thisEvent.which || thisEvent.keyCode;
	if ( (code >= 37 && code <= 40) || code == 9 || code == 16) return;
	
	// trim number
	var trimmedNumber = thisEvent.target.value.replace(/\D/g, "").substring(0, maxDigits);
	
	// minimum length requirement
	if (thisEvent.type == "blur" && trimmedNumber.length > 0 && trimmedNumber.length < minDigits) {
		alert(trimmedNumber + " does not meet the minimum length requirement of " + minDigits + ".");
		thisEvent.target.value = "";
		window.scrollTo(0,0);
		thisEvent.target.focus();
		return;
	}
	
	var commaValue = trimmedNumber.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	
	thisEvent.target.value = showComma ? commaValue : trimmedNumber;
}

// XPage Edit Box

<xp:inputText
	id="FieldId">
	<xp:eventHandler
		event="onblur"
		submit="false">
		<xp:this.script><![CDATA[inputNumber(thisEvent, true, 4, 6); ]]></xp:this.script>
	</xp:eventHandler>
	<xp:eventHandler
		event="onkeyup"
		submit="false">
		<xp:this.script><![CDATA[inputNumber(thisEvent, true, 4, 6);]]></xp:this.script>
	</xp:eventHandler>
</xp:inputText>





This script might be useful if you want to restrict an edit box to numbers only or automatically insert commas while typing a number. Add the inputNumber function to your JavaScript library and call it on both the onblur and onkeyup events.

JavaScript (Client)
Ryan Buening
August 9, 2016 2:28 PM
Rating
6

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...