简体   繁体   English

我如何在console.log中如何发送#form值?

[英]how can i console.log how the #form values will be sent?

i know we can manally log any input value by its selector 我知道我们可以通过其选择器手动记录任何输入值

console.log('inputName='+$('#inputId').val()+'....)

But is there -simpler- a way to log all input values? 但是,是否有 - 简单 - 记录所有输入值的方法? if it's posible to do it when any input changes 如果在任何输入改变时可以做到这一点

You can use serialize to serialize the form elements to a string for logging. 您可以使用serialize化将表单元素serialize化为字符串以进行日志记录。 It follows the same rules for including or not including elements as normal form submission. 它遵循与包括或不包括正常表单提交的元素相同的规则。 The only caveat is that the content of input type="file" fields isn't serialized, for perhaps obvious reasons. 唯一需要注意的是input type="file"字段的内容未被序列化,原因可能是显而易见的原因。

To fire it when any of the inputs changes: 在任何输入更改时触发它:

$("form :input").change(function() {
    console.log($(this).closest('form').serialize());
});

Live demo using the form shown in the documentation 使用文档中显示的表单进行现场演示

I made this little component: 我做了这个小组件:

$("form :input").change(function() {  
    var fields = $(this).closest('form').serialize();
    serialize_to_console( fields );
 });


/*
  SERIALIZE TO CONSOLE
  Transforms string to array and show each param in console if not empty */
var serialize_to_console = function( serialized ) { 

    var splited_serialized = serialized.split('&');

    $.each( splited_serialized, function(index, key) { 

        var input = key.substr(0, key.indexOf('=')); 
        var value = key.substr( key.indexOf('=') + 1 ); 

        if( value !== '' )
        console.log( '[' + input + '] = \'' + value + '\'' );
    });

}

Enjoy! 请享用!

您可以使用$("form").serialize()获取查询字符串的$("form").serialize()

This would log the form every time anything changes: 每次发生任何变化时,都会记录表单:

$("form :input").change(function(){
   console.log($("form").serialize());
});

Edit: 编辑:

Removed my focusout suggestion, as I realized that change is actually only fired when the element looses focus. 删除了我的焦点建议,因为我意识到实际上只有在元素失去焦点时才会触发更改。

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

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