2010-07-20 44 views
1

這裏是我現有的代碼時:觀測場:自動填充字段中選擇另一場

<% 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到自動填充點和進行現場編輯。我該怎麼做?

+0

不管是什麼,它總是50分嗎?如果是這種情況,您可以將該代碼移入模型中。 – 2010-07-20 02:13:40

+0

是的,總是...但用戶需要看到它是50分 – keruilin 2010-07-20 02:22:50

+0

你可以使用JavaScript然後 – Salil 2010-07-20 05:08:30

回答

0

我假設你可以因爲你使用Rails使用Prototype(JavaScript框架)。這可能是矯枉過正,但你可以添加一個觀察者到該領域來觀察焦點事件。從那裏,調用一個函數,將點字段的值設置爲50,然後使得點字段只讀(或禁用字段)。類似這樣的:

// 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')來查找點字段。

0

上的onfocus使用JavaScript來更新字段值

0

用javascript來做。如果您使用原型,應該這樣做:

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