【问题标题】:How to enable submit button when input fields are filled dynamically?动态填充输入字段时如何启用提交按钮?
【发布时间】:2019-08-26 15:34:33
【问题描述】:

我制作了一个网络表单,用户可以在其中使用下拉框填写输入字段。使用 Jquery 帮助动态填充字段。填写完所有输入字段后,用户必须单击提交按钮才能进一步使用我的表单优势。在填写所有输入字段之前,我不想让用户使用提交按钮。为此,我已经在我的代码中添加了一个函数。仅当所有输入字段都填充了一定数量时,此功能才启用提交按钮。但是当使用下拉框动态填充输入字段时会出现问题。当使用下拉框填充字段时,提交按钮本身不会启用。我必须单击其中一个输入字段才能启用它。

我也尝试过 Google 来解决这个问题,但我自己无法解决这个问题。 有人可以帮我解决这个问题吗?

这是我的代码

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>

【问题讨论】:

  • 对你的字段使用required标志,对你的按钮使用type="submit",HTML5会完成这项工作,你不需要禁用按钮,但不要忘记检查服务器中的数据一边。
  • 所以更新字段时触发验证码
  • @Gonzalo 由于我自己的一些原因,我不能使用必需属性。我正在尝试使用我的 JavaScript 代码中的一些更改来解决此问题。提前致谢
  • @epascarello 你能不能给我一个工作的例子。提前致谢

标签: javascript jquery html


【解决方案1】:

您的代码的最后一个keyup 是可以的($(document).on("keyup", "input[type='number']", ... );),但您忘记了它只会在inputs 中带有type='number' 属性的事件keyup 触发时触发。

当您在自动完成输入中选择某些内容时,此事件不会触发,您需要添加一些代码来检查它。比如:

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>

或者,至少,在设置字段值时触发keyup函数:

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>

【讨论】:

  • 你能分享一个Js fiddle吗?我会更容易理解。提前致谢
  • @user11651048 将示例更改为 sn-ps。希望对您有所帮助。
  • 感谢您回答@KL_。它真的对我有用。但是当我尝试在其他平台上使用它时,它无法正常工作。你能检查一下是什么问题吗。我将不胜感激。这是一个链接code.sololearn.com/WDvn2B98xMkA
  • @user11651048 您忘记检查自动完成选择中的输入更改(l.86 - 92)。
  • 对不起朋友,但我听不懂你想说什么。你能分享一下这个的解决方案吗?提前感谢@KL_
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2013-05-21
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多