0

我有一个充满值的“房间类型”表,我想这样当用户从 collection_select 中选择房间类型时,表单的其余部分会使用该房间类型的值进行更新,我可以检测到选择何时更改通过 $('#room_roomtype_id').change 使用 javascript 并通过 $('#room_roomtype_id :selected').text() 选择了哪种房间类型,但我不知道,而且我的搜索时间是徒劳的,那么如何使用房间类型表中的数据更新其他表单字段。

这是我的表单代码:

<%= form_for @room do |f| %>
        <% if @room.errors.any? %>
            <div class="error_messages">
                <h2>Form is invalid</h2>
                <ul>
                    <% for message in @room.errors.full_messages %>
                        <li><%= message %></li>
                    <% end %>
                </ul>
            </div>
        <% end %>

        <p id="roomtypes", data-url="<%= url_for :controller => 'rooms', :action => 'roomtypeupdate' %>">
            <%= f.label :roomtype_id, "Room type" %><br />
            <%= f.collection_select :roomtype_id, Roomtype.order(:name), :id, :name, include_blank: true %>
        </p>
        <p>
            <%= f.label :number, "Room number" %><br />
            <%= f.text_field :number %>
        </p>
        <p>
            <%= f.label :maxcap, "Capacity" %><br />
            <%= f.number_field :maxcap %>
        </p>
        <p>
            <%= f.label :size, "Size" %><br />
            <%= f.number_field :size %>
        </p>
        <p>
            <%= f.label :description, "Description" %><br />
            <%= f.text_area :description %>
        </p>
        <p>
            <%= f.label :singlebeds, "Number of single beds" %><br />
            <%= f.number_field :singlebeds %>
        </p>
        <p>
            <%= f.label :bathrooms, "Number of bathrooms" %><br />
            <%= f.number_field :bathrooms %>
        </p>
        <br />

        <p class="button"><%= f.submit %></p>
    <% end %>
4

1 回答 1

0

像这样的东西应该工作:

$('#room_roomtype_id').on('change', function () {

    // URL for the sake of example - yours will differ
    $.get('/rooms/' + this.value + '.json', function (response) {

    // dummy response for the sake of example
    response = {
        "number": "5A",
        "maxcap": "10"
    };

    $.each(response, function (key, value) {
        $('[name="room[' + key + ']"]').val(value);
    });
});
于 2013-04-06T03:48:19.613 回答