0

I have made a web form where a user can fill Input fields by using a drop down box. Fields are dynamically filled using Jquery help. When all Input fields are filled, user have to click Submit Button to further use my Form benefits. I don't want to let users use Submit button till all input fields are filled. For this, I have already added a function in my code. This function enables Submit button only when all the input fields are filled with some amount. but issue is arising when input fields are filled dynamically using drop down box. when fields are filled using the drop down box , Submit button is not getting enabled itself. I have to click one of the input field to enable it.

I tried Google also to solve this issue but unable to solve this on my own. Can someone please help me to solve this issue.

Here is my code

let headings = []
function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
}


function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input type="number" id="${heading}">`
      html += '<br>'
    }
  })

  return html
}


function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 1,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});



// code to set default values if user enters zero or negative values




//calculation for Rating value

$(document).ready(function(){ 
$("#Cal").click(function(){

var peVal=0,roceVal=0,sgVal=0,dyVal=0,psVal=0,pbVal=0,npmlqVal=0,roaVal=0,deVal=0,upsVal=0,crVal=0
;

jQuery(".fields input").each(function (){ 
var idHeading=$(this).attr("id");  

if(idHeading=="PE"){ peVal=parseInt($(this).val()); } 
if(idHeading=="ROCE"){ roceVal=parseInt($(this).val()); } 
if(idHeading=="SG"){ sgVal=parseInt($(this).val()); } 
if(idHeading=="DY"){ dyVal=parseFloat($(this).val()); } 
if(idHeading=="PS"){ psVal=parseFloat($(this).val()); }
if(idHeading=="PB"){ pbVal=parseFloat($(this).val()); }
if(idHeading=="NPMLQ"){ npmlqVal=parseFloat($(this).val()); }

if(idHeading=="ROA"){ roaVal=parseFloat($(this).val()); }
if(idHeading=="DE"){ deVal=parseFloat($(this).val()); }
if(idHeading=="UPS"){ upsVal=parseFloat($(this).val()); }
if(idHeading=="CR"){ crVal=parseFloat($(this).val()); }


}); 

var output=peVal+roceVal+sgVal+dyVal+psVal+pbVal+npmlqVal+roaVal+deVal+upsVal+crVal
;

$("output[name='amount']").text(output);
 }); 
 });
 
 
 $(document).on("keyup", "input[type='number']", function() {
  var empty = false;
  $('input[type="number"]').each(function() {
    if (($(this).val() == '')) {
      empty = true;
    }
  });

  if (empty) {
    $('#Cal').attr('disabled', 'disabled');
  } else {
    $('#Cal').removeAttr('disabled');
  }
});
 
<html>
    <head>
        <title>Page Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    </head>
    <body>
        
<div class="ui-widget">
  <form id="frm1">
    <label for="company">Drop-down box </label>
    <input id="company"><br /><br />
    
    <div class="fields"></div>
    <!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
 <button  type="button" id="Cal" disabled="disabled"  >
 Button
 </button>
<p> <output name="amount" for="calculation">0</output>
</p>
</form>
    </body>
</html>

8
  • Use required flag for your fields and type="submit" for your button, HTML5 will do the job and you don't need to disable the button, but don't forget to check data in server side. Commented Aug 26, 2019 at 15:39
  • So trigger the validation code when you update the fields Commented Aug 26, 2019 at 15:48
  • @Gonzalo I can't use Required attribute due to some of my own reasons. I am trying to resolve this issue using some changes in my JavaScript code. Thanks in advance Commented Aug 26, 2019 at 15:52
  • @epascarello can you please provide me a working example. Thanks in advance Commented Aug 26, 2019 at 15:53
  • api.jquery.com/trigger Commented Aug 26, 2019 at 15:55

1 Answer 1

1

The last keyup of your code is ok ($(document).on("keyup", "input[type='number']", ... );) but you forgot that it will only trigger when the event keyup trigger in the inputs with the attribute type='number'.

This event will not fire when you select something in the autocomplete input, you need to add some code to check it. Something like:

let headings = []
function initInputs(headingList) {
	jQuery(".fields").append(createInputsHTML(headingList))
}


function createInputsHTML(headingList) {
	let html = ''
	headingList.forEach(heading => {
		if (heading !== 'Company') {
			html += `<label for="${heading}">${heading}: </label>`
			html += `<input type="number" id="${heading}">`
			html += '<br>'
		}
	})

	return html
}


function getJSON() {
	return new Promise(resolve => {
		jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
			resolve(JSON.parse(data))
		});
	})
}

// processing raw JSON data
function processRawData(data) {
	return new Promise(resolve => {
		const companyData = []
		// creating data array
		// handling multiple sheets
		Object.values(data).forEach((sheet, index) => {
			sheet.forEach((company, i) => {
				companyData.push({ ...company
				})
				// create headings only once
				if (index === 0 && i === 0) {
					Object.keys(company).forEach(item => {
						headings.push(item.trim())
					})
				}
			})
		})
		resolve(companyData)
	})
}

$(async function() {

	let lists = [];

	function initAutocomplete(list) {
		const thisKey = 'Company'
		$("#company").autocomplete('option', 'source', function(request, response) {
			response(
				list.filter(item => {
					if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
						item.label = item[thisKey]
						return item
					}
				})
			)
		})
	}

	$("#company").autocomplete({
		minLength: 1,
		source: lists,
		focus: function(event, ui) {
			// the "species" is constant - it shouldn't be modified
			$("#company").val(ui.item.Company);
			return false;
		},
		select: function(event, ui) {
      var empty = false;
			// handling n number of fields / columns
			headings.forEach(heading => {
				$('#' + heading).val(ui.item[heading]);
        if ((ui.item[heading] == '')) {
          empty = true;
        }
			});
      checkFill(empty);
			return false;
		}
	});

	// starting data download, processing and usage
	getJSON()
		.then(json => {
			return processRawData(json)
		})
		.then(data => {
			
			// make the processed data accessible globally
			lists = data
			initAutocomplete(lists)
			initInputs(headings)
		})

});



// code to set default values if user enters zero or negative values




//calculation for Rating value

$(document).ready(function(){ 
$("#Cal").click(function(){

var peVal=0,roceVal=0,sgVal=0,dyVal=0,psVal=0,pbVal=0,npmlqVal=0,roaVal=0,deVal=0,upsVal=0,crVal=0
;

jQuery(".fields input").each(function (){ 
var idHeading=$(this).attr("id");  

if(idHeading=="PE"){ peVal=parseInt($(this).val()); } 
if(idHeading=="ROCE"){ roceVal=parseInt($(this).val()); } 
if(idHeading=="SG"){ sgVal=parseInt($(this).val()); } 
if(idHeading=="DY"){ dyVal=parseFloat($(this).val()); } 
if(idHeading=="PS"){ psVal=parseFloat($(this).val()); }
if(idHeading=="PB"){ pbVal=parseFloat($(this).val()); }
if(idHeading=="NPMLQ"){ npmlqVal=parseFloat($(this).val()); }

if(idHeading=="ROA"){ roaVal=parseFloat($(this).val()); }
if(idHeading=="DE"){ deVal=parseFloat($(this).val()); }
if(idHeading=="UPS"){ upsVal=parseFloat($(this).val()); }
if(idHeading=="CR"){ crVal=parseFloat($(this).val()); }


}); 

var output=peVal+roceVal+sgVal+dyVal+psVal+pbVal+npmlqVal+roaVal+deVal+upsVal+crVal
;

$("output[name='amount']").text(output);
 }); 
 });
 
 
 $(document).on("keyup", "input[type='number']", function() {
	var empty = false;
	$('input[type="number"]').each(function() {
		if (($(this).val() == '')) {
			empty = true;
		}
	});
  checkFill(empty);
});

function checkFill(isEmpty){
  if (isEmpty) {
		$('#Cal').attr('disabled', 'disabled');
	} else {
		$('#Cal').removeAttr('disabled');
	}
}
<html>
	<head>
		<title>Page Title</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
	</head>
	<body>
		<div class="ui-widget">
		  <form id="frm1">
			<label for="company">Drop-down box </label>
			<input id="company"><br /><br />
				<div class="fields"></div>
				<!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
 				<button  type="button" id="Cal" disabled="disabled"  >
 				Button
 				</button>
				<p> <output name="amount" for="calculation">0</output>
				</p>
			</form>
		</div>
	</body>
</html>

Or, at least, trigger the keyup function when you set the field value:

let headings = []
function initInputs(headingList) {
	jQuery(".fields").append(createInputsHTML(headingList))
}


function createInputsHTML(headingList) {
	let html = ''
	headingList.forEach(heading => {
		if (heading !== 'Company') {
			html += `<label for="${heading}">${heading}: </label>`
			html += `<input type="number" id="${heading}">`
			html += '<br>'
		}
	})

	return html
}


function getJSON() {
	return new Promise(resolve => {
		jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
			resolve(JSON.parse(data))
		});
	})
}

// processing raw JSON data
function processRawData(data) {
	return new Promise(resolve => {
		const companyData = []
		// creating data array
		// handling multiple sheets
		Object.values(data).forEach((sheet, index) => {
			sheet.forEach((company, i) => {
				companyData.push({ ...company
				})
				// create headings only once
				if (index === 0 && i === 0) {
					Object.keys(company).forEach(item => {
						headings.push(item.trim())
					})
				}
			})
		})
		resolve(companyData)
	})
}

$(async function() {

	let lists = [];

	function initAutocomplete(list) {
		const thisKey = 'Company'
		$("#company").autocomplete('option', 'source', function(request, response) {
			response(
				list.filter(item => {
					if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
						item.label = item[thisKey]
						return item
					}
				})
			)
		})
	}

	$("#company").autocomplete({
		minLength: 1,
		source: lists,
		focus: function(event, ui) {
			// the "species" is constant - it shouldn't be modified
			$("#company").val(ui.item.Company);
			return false;
		},
		select: function(event, ui) {
			// handling n number of fields / columns
			headings.forEach(heading => {
				$('#' + heading).val(ui.item[heading]).keyup();
			})
			return false;
		}
	});

	// starting data download, processing and usage
	getJSON()
		.then(json => {
			return processRawData(json)
		})
		.then(data => {
			
			// make the processed data accessible globally
			lists = data
			initAutocomplete(lists)
			initInputs(headings)
		})

});



// code to set default values if user enters zero or negative values




//calculation for Rating value

$(document).ready(function(){ 
$("#Cal").click(function(){

var peVal=0,roceVal=0,sgVal=0,dyVal=0,psVal=0,pbVal=0,npmlqVal=0,roaVal=0,deVal=0,upsVal=0,crVal=0
;

jQuery(".fields input").each(function (){ 
var idHeading=$(this).attr("id");  

if(idHeading=="PE"){ peVal=parseInt($(this).val()); } 
if(idHeading=="ROCE"){ roceVal=parseInt($(this).val()); } 
if(idHeading=="SG"){ sgVal=parseInt($(this).val()); } 
if(idHeading=="DY"){ dyVal=parseFloat($(this).val()); } 
if(idHeading=="PS"){ psVal=parseFloat($(this).val()); }
if(idHeading=="PB"){ pbVal=parseFloat($(this).val()); }
if(idHeading=="NPMLQ"){ npmlqVal=parseFloat($(this).val()); }

if(idHeading=="ROA"){ roaVal=parseFloat($(this).val()); }
if(idHeading=="DE"){ deVal=parseFloat($(this).val()); }
if(idHeading=="UPS"){ upsVal=parseFloat($(this).val()); }
if(idHeading=="CR"){ crVal=parseFloat($(this).val()); }


}); 

var output=peVal+roceVal+sgVal+dyVal+psVal+pbVal+npmlqVal+roaVal+deVal+upsVal+crVal
;

$("output[name='amount']").text(output);
 }); 
 });
 
 
 $(document).on("keyup", "input[type='number']", function() {
	var empty = false;
	$('input[type="number"]').each(function() {
		if (($(this).val() == '')) {
			empty = true;
		}
	});

	if (empty) {
		$('#Cal').attr('disabled', 'disabled');
	} else {
		$('#Cal').removeAttr('disabled');
	}
});
<html>
	<head>
		<title>Page Title</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
	</head>
	<body>
		<div class="ui-widget">
		  <form id="frm1">
			<label for="company">Drop-down box </label>
			<input id="company"><br /><br />
				<div class="fields"></div>
				<!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
 				<button  type="button" id="Cal" disabled="disabled"  >
 				Button
 				</button>
				<p> <output name="amount" for="calculation">0</output>
				</p>
			</form>
		</div>
	</body>
</html>

Sign up to request clarification or add additional context in comments.

6 Comments

Can you please share a Js fiddle of it. It will be easier for me to understand. Thanks in advance
@user11651048 changed the examples to snippets. Hope it helps.
thanks for you answer @KL_. It really worked for me. But when I tried to use it on other platform, it is not working properly. Can you please check what is the issue. I will be very grateful. Here is a link code.sololearn.com/WDvn2B98xMkA
@user11651048 you forgot to check the input changes in the select of autocomplete (l.86 - 92).
Sorry friend but I can't understand what you are trying to say. Can you please share me the solution of this? Thanks in advance @KL_
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.