【问题标题】:Return id from nested_attributes in javascript从javascript中的嵌套属性返回id
【发布时间】:2014-06-19 17:20:39
【问题描述】:

我在 rails 中有一个编辑视图,其中包含许多来自 nested_attributes 的输入框。

<div class="form-group">
    <%= f.fields_for :item_prices, :class => "col-sm-2" do |ff|%>
        <%= ff.hidden_field :store_id %>
            <div class="col-sm-8 input_cc_size">
                <label><%= ff.object.store.name %></label>
                <%= ff.text_field :regular_price, :class => "form-control input_cc_size_nested", :value => (number_with_precision(ff.object.regular_price, :precision => 2)) %>
            </div>
   <% end %>
</div>

当我在第一个框中键入一个值时,我想在 javascript 中动态地取这个值。 我找到了这个参考Jquery: Mirror one text input to another 我正在尝试在 javascript 中做类似的事情。如何在 javascript 中返回嵌套属性的 id 并遍历它们?如果标准的 id 我可以做类似的事情

$('#item_item_prices_attributes_0_store_id').bind('keypress blur', function() {
    $('#item_item_prices_attributes_1_store_id').val($(this).val());
    $('#item_item_prices_attributes_2_store_id').val($(this).val());
});

但是对于嵌套属性,我不知道该怎么做。
提前致谢!

【问题讨论】:

  • 显示实际的 HTML,而不仅仅是模板。

标签: javascript ruby-on-rails nested-attributes


【解决方案1】:

绑定到标签名,而不是id:

$('.form-group input:eq(0)').bind('keypress blur', function () {
  $('.form-group input:gt(0)').val($(this).val());
});

应该将第一个输入的值复制到类form-group的元素内的所有其他输入。

【讨论】:

【解决方案2】:

@AlexAtNet 感谢您抽出宝贵时间回答!

我所做的是用 for 循环遍历所需的 id。我还在表单中添加了一个隐藏字段来计算价格,因此我需要 for 循环的 id。 我的js是:

jQuery(function(){
    $("item_item_prices_attributes_0_regular_price.bind("change", function(){
        stcount = document.getElementById('count_stores').value;
        for (var i=0; i< stcount; i++){
            $("#item_item_prices_attributes_"+i+"_regular_price").val($(this).val());
        }
    });
)};

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 2018-10-17
    • 2011-03-31
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多