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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8532163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:23:34  来源:igfitidea点击:

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

javascriptjqueryforms

提问by Toni Michel Caubet

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

但是有没有 - 更简单的 - 一种记录所有输入值的方法?如果可以在任何输入更改时执行此操作

回答by T.J. Crowder

You can use serializeto serialize the form elements to a string for logging. 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.

您可以使用serialize将表单元素序列化为字符串以进行记录。它遵循与正常表单提交相同的包含或不包含元素的规则。唯一的警告是input type="file"字段的内容没有序列化,原因可能很明显。

To fire it when any of the inputs changes:

在任何输入更改时触发它:

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

Live demousing the form shown in the documentation

使用文档中显示的表单进行现场演示

回答by Abdul Munim

You may get in form of query string using $("form").serialize().

您可以使用$("form").serialize().

回答by Christofer Eliasson

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.

删除了我的重点建议,因为我意识到实际上只有在元素失去焦点时才会触发更改。

回答by Jorge Correa

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!

享受!