Copying from form to form in jQuery

前端 未结 2 925
灰色年华
灰色年华 2020-12-06 07:54

I had a requirement to copy all fields from one form to another similar form. So instead of copying field by field I wrote a routine, form2form, using jQuery.



        
相关标签:
2条回答
  • 2020-12-06 07:58

    > Is there a built in function so I didn't need this?

    Not really. There's clone(), but that's more for copying an element to another spot in the DOM. You need to populate a second form.

    > Can I pass form objects rather then the form name as a text?

    Yes:

    function form2form(formA, formB) {
        $(':input[name]', formA).each(function() {
            $('[name=' + $(this).attr('name') +']', formB).val($(this).val())
        })
    }
    

    You can make it a plugin too!

    (function($) {
        $.fn.copyNamedTo = function(other) {
            return this.each(function() {
                $(':input[name]', this).each(function() {
                    $('[name=' + $(this).attr('name') +']', other).val($(this).val())
                })  
            })
        }
    }(jQuery))
    

    ps the ":input" pseudo selector does not skip radio or select inputs. It explicitly includes select and input elements (at least in 1.3.2), of which radio buttons are a part of.

    0 讨论(0)
  • 2020-12-06 08:08

    I had to add this to the plugin to get it to operate checkboxes.

    $('[name=' + $(this).attr('name') +']', other).attr("checked", $(this).attr("checked"));
    
    0 讨论(0)
提交回复
热议问题