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.
> 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.
I had to add this to the plugin to get it to operate checkboxes.
$('[name=' + $(this).attr('name') +']', other).attr("checked", $(this).attr("checked"));