Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

serialization - how can I override jquery's .serialize to include unchecked checkboxes

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.

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( /
?
/g, "
" ) };
                    }) :
                    { name: elem.name, value: val.replace( /
?
/g, "
" ) };
        }).get();
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...