观察者字段:选择另一个字段时自动填充字段

时间:2010-07-20 02:11:23

标签: ruby-on-rails javascript-events autocomplete textfield

这是我现有的代码:

<% form_for(@match) do |f| %>
    <%= f.error_messages %>
    <fieldset>
        <p>
            <label>Name</label>
            <%= f.text_field(:name) %>
        </p>
        <p>
            <label>OR email address</label>
            <%= f.text_field(:email) %>
        </p>
    </fieldset>
    <p>
        <label>Points:</label>
        <%= f.text_field(:points) %>
    </p>
    <p>
        <%= f.submit 'Match' %>
    </p>

<% end %>

当用户选择电子邮件字段时,我想使用50自动填充Points并使该字段不可编辑。我该怎么做?

3 个答案:

答案 0 :(得分:0)

在onFocus上使用javascript来更新字段值

答案 1 :(得分:0)

我假设您可以使用Prototype(Javascript框架),因为您正在使用Rails。这可能有点矫枉过正,但您可以在该字段中添加观察者以观察焦点事件。从那里,调用一个函数,将points字段的值设置为50,然后使points字段只读(或禁用字段)。像这样:

// Add the observer on the field when the DOM loads
document.observe("dom:loaded", function() {

    // Observe object with ID = "match_email" for focus event
    $('match_email').observe('focus',respondToEmailFocus);
});

// Function to call when the user focuses on the email field
function respondToEmailFocus(event){
    // Find object with ID = "match_points" and set the value = 50
    $('match_points').value = 50;
    // Find the object with ID = "match_points" and make it read only
    $('match_points').readOnly=true;

    // Instead of setting to read only, you could disable the field using:
    // $('match_points').disable();
}

以下是events and Prototype的更多信息,以防您需要修改它。

虽然您可以将该代码直接放入视图中,但最佳做法是将Javascript与视图代码分开(不显眼的Javascript)。您可以将该代码放在单独的Javascript文件中,然后使用Rail的javascript_include_tag包含该文件。

如果您不想使用Prototype,只需在电子邮件字段中添加onFocus属性并调用类似于上面的函数(respondToEmailFocus)。由于您未使用Prototype,因此必须使用document.getElementById('match_points')而不是$('match_points')来查找点字段。

答案 2 :(得分:0)

在javascript中执行此操作。如果您使用Prototype:

,这样的事情应该这样做
// Find the element with id=match_email and observe it for focus
$('match_email').observe('focus', function() {
  // When focus occurs:
  // Set the value of the element with id=match_points to 50
  // Make the same field read only
  $('match_points').value = 50;
  $('match_points').read_only = true ;
});