This tutorial example shows how to populate input fields in form automatically when a page is loaded or when a checkbox is checked. The below example has three fields and one of then gets populated when the page is loaded and another one of them is populated when checkbox is checked.

Sometimes we need to populate the input fields depending upon another field then it may be useful. So below example will give you an idea so that you can also populate your form fields according to your requirements.

Final Output

When home page is displayed

auto populate using javascript

When checbox is checked

auto populate using javascript

<!doctype html>
		<script type="text/javascript">
			//delegate amount
			var delAmount = 0;
			//spouse amount
			var spouseAmount = 0;
			//compare date so that depending on the date value we can set some amount to the particular field
			var x ='15-12-2014';
			var a = x.split('-');
			var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
			var Today = new Date();
			if (date > Today) {
				delAmount = 1200;
				spouseAmount = 500;
			} else {
				delAmount = 1500;
				spouseAmount = 700;
			//total amount
			var totalAmount = delAmount;
			//below function is called when the page loads
			function populateAmount() {
				//populate delegate field with delegate amount
				document.getElementById('delAmount').value = delAmount;
				//populate total field with total amount
				document.getElementById('totalAmount').value = totalAmount;
			//below function is called when checkbox is checked
			function calcTotalAmount() {
				//populate delegate amount
				document.getElementById('delAmount').value = delAmount;
				//recalculate and populate total amount field
				if(document.getElementById('chkBox').checked && document.getElementById('chkBox').value == 1) {
					totalAmount = delAmount + spouseAmount;
				} else {
					totalAmount = totalAmount - spouseAmount;
				document.getElementById('totalAmount').value = totalAmount;
	<body onload="populateAmount();">
		<div style="width:650px;margin:auto;">
			<!-- Delegate Amount -->
				<input type="text" id="delAmount" disabled="disabled">
			<!-- Checkbox -->
				<input type="checkbox" id="chkBox" value="1" onchange="calcTotalAmount();">
			<!-- Total Amount -->
				<label>Total Amount</label><br/>
				<input type="text" id="totalAmount" disabled="disabled">

That’s all. Thanks for your patience. Please do not forget to leave a comment.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *