简体   繁体   English

如果 HTML 表单的输入字段值为空,如何防止提交它

[英]How to prevent submitting the HTML form's input field value if it empty

I have HTML form with input fields.我有带有输入字段的 HTML 表单。 Some of inputs can be empty, ie the value is "".一些输入可以为空,即值为“”。

<input name="commentary" value="">

Just now, when commentary field is not set, it appears in submit url like: &commentary=刚才,当没有设置commentary字段时,它会出现在submit 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.我如何从提交 url 中删除空输入,所以当commentary输入为空时,它根本不会被传递。

Thank you very much.非常感谢。

Update更新

Thanks to minitech answer, I could resolve it.感谢minitech 的回答,我可以解决它。 JavaScript code is below: JavaScript 代码如下:

$('#my-form-id').submit(function() {
  var commentary = $('#commentary').val(); 
  if (commentary === undefined || commentary === "") {
    $('#commentary').attr('name', 'empty_commentary');
  } else {
    $('#commentary').attr('name', 'commentary');        
  }
});

The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.我在字段名称前加上“empty_”的唯一原因是 IE 无论如何都会在 URL 中传递空名称。

This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure.据我所知,这只能通过 JavaScript 来完成,因此如果您依赖此功能,则需要重构。 The idea, anyway, is to remove the name attribute from inputs you don't want included:无论如何,这个想法是从您不想包含的输入中删除name属性:

jQuery: jQuery:

$('#my-form-id').submit(function () {
    $(this)
        .find('input[name]')
        .filter(function () {
            return !this.value;
        })
        .prop('name', '');
});

No jQuery:没有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.如果您使用侦听器并取消,您可能还想在之后重置表单。

You probably don't want to match radio buttons.您可能不想匹配单选按钮。 And if the form contains select's, you'll need to match them too.如果表单包含选择,您也需要匹配它们。

With jQuery, you might use something like this:使用 jQuery,你可能会使用这样的东西:

$('#form-id').submit(function() {
    $(this).find('input[type!="radio"][value=""],select:not(:has(option:selected[value!=""]))').attr('name', '');
});

I prefer not to alter the input elements (changing their names, or flagging them as disabled and so), because if you go back you could get a broken form.我不想更改输入元素(更改它们的名称,或将它们标记为禁用等),因为如果返回,您可能会得到一个损坏的表单。

Here is my solution instead, which relies on FormData :这是我的解决方案,它依赖于FormData

window.addEventListener('load', function() {
  let forms = document.getElementsByClassName('skipEmptyFields');
  for (let form of forms) {
    form.addEventListener('formdata', function(event) {
      let formData = event.formData;
      for (let [name, value] of Array.from(formData.entries())) {
        if (value === '') formData.delete(name);
      }
    });
  }
});

Instead of using a submit -type input, use a button -type input for form submission.不要使用submit类型的输入,而是使用button类型的输入来提交表单。 The JavaScript handler for the button -type input should call form's submit() method after checking that commentary is non-empty. button类型输入的 JavaScript 处理程序应在检查注释非空后调用表单的submit()方法。 You should also alert the user to their mistake (better with a red text on the page rather than the pop-up produced by alert() ).您还应该提醒用户他们的错误(最好在页面上使用红色文本而不是由alert()生成的弹出窗口)。

Remember that you should not rely solely on client-side input validation, though since it is always possible to send the form from a modified page or directly in HTTP.请记住,你不应该仅仅依靠客户端输入验证,但因为它总是可以从直接或修改的页面在HTTP发送的形式。

Thankyou @Ryan谢谢@Ryan

This is my full solution for this.这是我对此的完整解决方案。 I use Jersey and @BeanParam and this fixes the problem of "" & null inputs我使用 Jersey 和 @BeanParam 这解决了“”和空输入的问题

$('#submitForm').click(function() {
    var url = "webapi/?";       
    var myForm = document.getElementById('myFormId');
    var allInputs = myForm.getElementsByTagName('input');

    for (var i = 0; i < allInputs.length; i++) {
        var input = allInputs[i];
        if (input.value != "" && input.name != "submitForm") {              
            url += input.name +'='+input.value+'&';
        }

    }
    console.log(url);

    $.ajax({
        method : "GET",
        url : url,

        data : {
        // data : "json",
        // method: "GET"
        },
        success : function(data) {
            console.log("Responce body from Server: \n" + JSON.stringify(data));
            $("#responce").html("");
            $("#responce").html(JSON.stringify(data));
        },
        error : function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus);

            console.log('Error: ' + errorThrown);

        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM