使用 JavaScript 将数据链接从模态发送到表单

send data link from modal to form with javascript

本文关键字:表单 模态 JavaScript 数据 链接 使用      更新时间:2023-09-26

我的错误是:未捕获的类型错误:无法读取未定义的属性"forEach"

这是 rails 4 和 javascript 的混合体。我在模态中有一个按钮,我需要将数据发送到表单中的集合。

用户将在模态和形式中选择一个产品,我需要该产品可用的颜色集合。

产品有多种衬衫颜色。

模 态

<td><%= link_to 'Add product', '#', class: 'btn btn-success btn-add-product', data: {product: product, sizes: product.sizes, shirt_colors: product.shirt_colors} %></td>

JavaScript

$(".btn-add-product").click(function(){
  var product = $(this).data("product");
  var shirt_colors = $(this).data("shirt_colors");
  shirt_colors.forEach(function(shirt_color){
    $('select#color-select')
      .append('<option value="'+shirt_color.name+'">'+shirt_color.name.toUpperCase()+'</option>')
})

})

形式

= f.input :color_name, label: false, collection: [], input_html: {id: 'color-select'}

您需要使用连字符而不是下划线来获取"data"属性

$(this).data("shirt-colors");