Chris
Chris

Reputation: 27394

jQuery - Copying form to identical form

I want to copy an existing form to another form. I found this question which works on normal inputs but it throws an error on my checkboxes

The jQuery function (from) I am using is

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

The error is:

Uncaught Error: Syntax error, unrecognized expression: [name=cartype[]] 

The checkboxes are arranged like so:

<input type="checkbox" name="cartype[]" id="cartype_10" value="10">4x4
<input type="checkbox" name="cartype[]" id="cartype_11" value="11">Saloon

I expect this is due to the [] in the name but can't figure out what to do about it.

Upvotes: 0

Views: 125

Answers (2)

Matt
Matt

Reputation: 75327

You'll have to replace the [ and ] in your name with \\[ and \\] (as laid out here), as (as you know) they've got special meanings in jQuery selectors.

$('[name=' + $(this).attr('name').replace(/([\[\]])/g, '\\\\$1') +']', other).val($(this).val())

Note that technically you should also have a selector of the form $('[name="val"]') (note the quotes around the attribute value). jQuery has always seemed to be lenient about this, but it's conforming to the docs.

To nail the checkboxes and radio buttons, you need to be setting the checked property of them, rather than altering the value. You can change your function to this;

$.fn.copyNamedTo = function(other) {
    return this.each(function() {
        $(':input[name]', this).each(function() {
            var target = $('[name=' + $(this).attr('name').replace(/([\[\]])/g, '\\\\$1') +']', other);

            // Radios have the same name as each other, so filter based on value
            // Checkboxes are in the same boat here due to the naming conventions shown in the OP.
            if ($(this).is(':checkbox, :radio')) {
                target.filter('[value="' + this.value + '"]').prop('checked', this.checked);
            } else {
                target.val($(this).val());
            }
        })
    })
}

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

Try using data attribute.

data-name="cartype[]"

And grab it using: $(this).data('name')

Upvotes: 0

Related Questions