观察现场:自动填充选择另一场场时, [英] Observer Field: Autofill field when selecting another field

查看:114
本文介绍了观察现场:自动填充选择另一场场时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我现有的code:

Here's my existing code:

<% 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到自动填充点,并进行现场编辑。我怎么做呢?

When the user selects the email field, I want to autopopulate the Points with 50 and to make the field uneditable. How do I do so?

推荐答案

我假设你可以因为你用Rails使用Prototype(JavaScript框架)。这可能是矫枉过正,但你可以观察者添加到现场观看的焦点事件。从那里,称之为设定点字段50的值,然后使点字段只读(或禁用字段)的功能。事情是这样的:

I'm assuming you can use Prototype (Javascript framework) since you're using Rails. This may be overkill, but you could add an observer to that field to watch for the focus event. From there, call a function that sets the value of the points field to 50 and then makes the points field read only (or disables the field). Something like this:

// 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();
}

下面是关于事件和原型的情况下,你需要修改它的详细信息。

Here's more info on events and Prototype in case you need to modify it.

虽然你可以只把那code右转入来看,最好的做法是让你的Javascript从视图code(不显眼的JavaScript)的分离。你可以把code在一个单独的JavaScript文件,然后包含这个文件使用铁路的javascript_include_tag。

While you could just put that code right into the view, best practice is to keep your Javascript separate from the view code (unobtrusive Javascript). You can put that code in a separate Javascript file and then include that file using Rail's javascript_include_tag.

如果你不想使用原型,你可以添加在电子邮件领域的onfocus属性,并调用类似于上面的一(respondToEmailFocus)的功能。既然你不使用的原型,你将不得不使用的document.getElementById('match_points')而不是 $('match_points')找点领域。

If you don't want to use Prototype, you can just add the onFocus attribute on the email field and call a function similar to the one above (respondToEmailFocus). Since you're not using Prototype, you would have to use document.getElementById('match_points') instead of $('match_points') to find the points field.

这篇关于观察现场:自动填充选择另一场场时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆