如何防止提交HTML表单的输入字段值,如果它为空 [英] How to prevent submitting the HTML form's input field value if it empty

查看:1012
本文介绍了如何防止提交HTML表单的输入字段值,如果它为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



< input name =commentaryvalue =>



现在,当评论字段没有设置时,它就会出现在submit url中:& comment =



如何从提交网址中移除空输入,所以当<$ c











$

更新



感谢 minitech 答案,我可以解决它。 JavaScript代码如下:

  $('#my-form-id')。submit(function(){$ b $ (评论===未定义||评论===){
$('#comment')。attr('#comment')。val();
if ('name','empty_commentary');
} else {
$('#commentary')。attr('name','comment');
}
} );

我将字段名称前缀为empty_的唯一原因是IE无论如何都会在URL中传递空名称。

解决方案

据我所知,这只能通过JavaScript来完成,所以如果你依赖这个功能,你需要重组。无论如何,这个想法是从您不想包含的输入中移除名称属性:



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

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

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


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

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

Just now, when commentary field is not set, it appears in submit url like: &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.

Thank you very much.

Update

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

The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.

解决方案

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

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

这篇关于如何防止提交HTML表单的输入字段值,如果它为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆