簡體   English   中英

在提交到 RoR 之前,如何在 model 方法中獲取屬性值?

[英]How do I get the value of an attribute in a model method before submitting in RoR?

假設我有一個屬性:例如出生年份和另一個字段:年齡(只讀),我填寫出生年份。 我在 model 中創建了一個方法來計算年齡,年齡如何填充到視圖中?

這是我做的一個簡短的代碼片段,應該讓你走上正確的道路(使用 javascript,但沒有評論中提到的 ruby on rails)。

document.getElementById("date").value獲取id為“date”的元素的值。 您只需將日期(我假設它只是出生年份)減去 2020 年即可。

Date of birth: <input type="int" id="date">
Age: <input type="int" id="age">

<p>Click the button to get the age!</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("age").value = 2020 - document.getElementById("date").value;
}
</script>

這只是一個基本腳本,幾個月后不會可用,因為我們將在 2021 年提供,因此我將讓您找到如何在 javascript 中獲取當前年份。它也不是很准確,因為它沒有考慮出生月/日,但你明白了!

我希望這對你有幫助,如果有什么不清楚或沒有按照你想要的方式工作,請告訴我。

編輯:哦,我忘了說但是這段代碼在你點擊按鈕后執行,這可能不是真正的用戶友好(取決於你在做什么,真的。),如果你想讓 function 盡快執行該字段已填充。 它幾乎不需要修改。

如果你想在出生年份改變時立即顯示年齡,你可以像這樣將onchange事件添加到輸入中:

Date of birth: <input type="int" id="date" onchange=myFunction()>
Age: <input type="int" id="age">

<p>Fill the first area with a year to get the age!</p>

<script>
function myFunction() {
  document.getElementById("age").value = 2020 - document.getElementById("date").value;
}
</script>

一旦您按下回車鍵或在文本區域外單擊, onchange事件就會觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM