vollnhals / dependent-fields-rails

DependentFields makes it easy to hide or show dependent fields in forms based on select or checkbox values.
MIT License
36 stars 19 forks source link

"Cannot read property 'replace' of undefined" when form has input doesn't have name attribute #16

Open EdCordata opened 3 years ago

EdCordata commented 3 years ago

Many plugins append extra inputs to form, without name attributes.

For this reason, this plugin should check if the input has a name attribute, before trying to use it, so the user doesn't get this JavaScript error:

Uncaught TypeError: Cannot read property 'replace' of undefined
    at HTMLInputElement.showOrHideDependentFieldsRadio (dependent-fields.source.js.coffee:57)
    at executeBound (underscore.source.js:701)
    at HTMLInputElement.bound (underscore.source.js:733)
    at Function.each (jquery.source.js:370)
    at jQuery.fn.init.each (jquery.source.js:137)
    at Object.bind (dependent-fields.source.js.coffee:74)
    at Object.init.dependentFields (dependent-fields.source.js:2)
    at HTMLDocument.<anonymous> (application.source.js:35)
    at HTMLDocument.dispatch (jquery.source.js:5226)
    at HTMLDocument.elemData.handle (jquery.source.js:4878)

Error happens in this line:

$(".js-dependent-fields[data-radio-name=#{$radio.attr('name').replace(/\[/g, '\\[').replace(/]/g, '\\]')}]").each showOrHideFields

If im not mistaken, it can be fixed by just simply doing this:

$(".js-dependent-fields[data-radio-name=#{$radio.attr('name').toString().replace(/\[/g, '\\[').replace(/]/g, '\\]')}]").each showOrHideFields

or by updating selectors, when binding:

bind = ->
  $selects = $('select[name]')