如果 HTML 表单的输入字段值为空,如何防止提交它 [英] How to prevent submitting the HTML form's input field value if it empty
问题描述
我有带有输入字段的 HTML 表单.一些输入可以为空,即值为".
I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".
刚才,当 commentary
字段未设置时,它出现在提交 url 中,如:&commentary=
Just now, when commentary
field is not set, it appears in submit url like: &commentary=
如何从提交 url 中删除空输入,以便当 commentary
输入为空时,它根本不会被传递.
How I can remove empty inputs from the submit url, so when the commentary
input is empty it would not be passed at all.
非常感谢.
感谢 minitech 的回答,我可以解决它.JavaScript 代码如下:
Thanks to minitech answer, I could resolve it. JavaScript code is below:
$('#my-form-id').submit(function() {
var commentary = $('#commentary').val();
if (commentary === undefined || commentary === "") {
$('#commentary').attr('name', 'empty_commentary');
} else {
$('#commentary').attr('name', 'commentary');
}
});
我在字段名称前加上empty_"的唯一原因是 IE 无论如何都会在 URL 中传递空名称.
The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.
推荐答案
据我所知,这只能通过 JavaScript 来完成,因此如果您依赖此功能,则需要重新构建.无论如何,这个想法是从您不想包含的输入中删除 name
属性:
This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name
attribute from inputs you don’t want included:
jQuery:
$('#my-form-id').submit(function () {
$(this)
.find('input[name]')
.filter(function () {
return !this.value;
})
.prop('name', '');
});
没有 jQuery:
var myForm = document.getElementById('my-form-id');
myForm.addEventListener('submit', function () {
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.name && !input.value) {
input.name = '';
}
}
});
如果您使用侦听器并取消,您可能还想在之后重置表单.
You might also want to reset the form afterwards, if you use a listener and cancel.
这篇关于如果 HTML 表单的输入字段值为空,如何防止提交它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!