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.
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.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
checkedproperty of them, rather than altering the value. You can change your function to this;