如果HTML表单的输入字段为空,如何避免提交

时间:2022-11-13 23:00:41

I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".

我有带有输入字段的HTML表单。有些输入可以是空的,即值为“”。

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

<输入名称= "评论" value=" ">

Just now, when commentary field is not set, it appears in submit url like: &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中删除空输入,以便当注释输入为空时,根本不会传递它。

Thank you very much.

非常感谢。

Update

Thanks to minitech answer, I could resolve it. JavaScript code is below:

感谢minitech的回答,我可以解决它。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中传递空名称。

4 个解决方案

#1


36  

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:

据我所知,这只能通过JavaScript完成,所以如果您依赖于此功能,就需要进行重构。不管怎样,我们的想法是从输入中移除不想包含的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');

myFrm.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.

如果您使用侦听器并取消,您可能还需要重新设置表单。

#2


3  

You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.

你可能不想匹配单选按钮。如果表单包含select's,那么也需要匹配它们。

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', '');
});

#3


2  

Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. 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()).

使用按钮类型的输入来提交表单,而不是使用提交类型的输入。按钮类型输入的JavaScript处理程序应该在检查注释为非空后调用form的submit()方法。您还应该提醒用户注意他们的错误(最好在页面上使用红色文本,而不是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发送表单总是可能的。

#4


0  

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,这解决了“”和null输入的问题

$('#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);

        }
    });
});

#1


36  

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:

据我所知,这只能通过JavaScript完成,所以如果您依赖于此功能,就需要进行重构。不管怎样,我们的想法是从输入中移除不想包含的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');

myFrm.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.

如果您使用侦听器并取消,您可能还需要重新设置表单。

#2


3  

You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.

你可能不想匹配单选按钮。如果表单包含select's,那么也需要匹配它们。

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', '');
});

#3


2  

Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. 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()).

使用按钮类型的输入来提交表单,而不是使用提交类型的输入。按钮类型输入的JavaScript处理程序应该在检查注释为非空后调用form的submit()方法。您还应该提醒用户注意他们的错误(最好在页面上使用红色文本,而不是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发送表单总是可能的。

#4


0  

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,这解决了“”和null输入的问题

$('#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);

        }
    });
});