如何覆盖jquery的.serialize包含未选中的复选框 [英] how can I override jquery's .serialize to include unchecked checkboxes

查看:603
本文介绍了如何覆盖jquery的.serialize包含未选中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多不同的方法,使html复选框发布到服务器,但我真的想做,而不修改任何东西,除了$ .serialize。我理想情况下,我想要复选框发布为,并取消选中发布为0,空或null。

I have read quite a few different methods of having html checkboxes get posted to the server, but I am really looking to do it without modifying anything except for $.serialize. I ideally, I would like checked boxes to be posted as on, and unchecked to be posted as 0, empty, or null.

我有点困惑的jquery的内部工作,但我已经到目前为止,但它设置未选中的复选框为开...任何人都可以告诉我如何继续这个修改下面?

I'm a little confused by jquery's inner-workings, but I've got this so far, but it sets unchecked checkboxes to 'on'... Can anyone tell me how to continue this modification below?

$.fn.extend({
    serializeArray: function() {
        return this.map(function(){
            return this.elements ? jQuery.makeArray( this.elements ) : this;
        })
        .filter(function(){
            return this.name && !this.disabled &&
                ( this.checked || !this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) );
        })
        .map(function( i, elem ){
            var val = jQuery( this ).val();

            return val == null ?
                null :
                jQuery.isArray( val ) ?
                    jQuery.map( val, function( val, i ){
                        return { name: elem.name, value: val.replace( /\r?\n/g, "\r\n" ) };
                    }) :
                    { name: elem.name, value: val.replace( /\r?\n/g, "\r\n" ) };
        }).get();
    }
});


推荐答案


在我的保存例程中,足够提交unchecked为空字符串并检查为on:

just attach the data. In my save routine it's enough to submit unchecked as empty string and checked as "on":

var formData = $('form').serialize();

// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
    .filter(function(idx){
        return $(this).prop('checked') === false
    }),
    function(idx, el){
        // attach matched element names to the formData with a chosen value.
        var emptyVal = "";
        formData += '&' + $(el).attr('name') + '=' + emptyVal;
    }
);

这篇关于如何覆盖jquery的.serialize包含未选中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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