前回【Visualforce】JavascriptからgetElementByIdで値を参照する方法を書いた時、ループの中のコンポーネントを参照する方法についてまったく触れていませんでした。
ループの中のコンポーネントを参照したい場合は、コンポーネントパスに行番号を含めてあげます。こんな感じ(赤字の部分)。
document.getElementById(‘pg:frm:pb:pgs:pbt:1:tanka’).value; |
もう少し具体的なサンプルを書くとこんな感じです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!-- Visualforceページ --> <apex:page id="pg" controller="LoopSampleController"> <apex:form id="frm" > <table id="tbl" border="1"> <tr bgcolor="#a9a9a9"> <th>テキスト</th> <th>ボタン</th> </tr> <apex:variable id="index" var="index" value="0" /> <apex:repeat id="rpt" var="sample" value="{!sampleList}"> <tr> <td><apex:inputField id="txt" value="{!sample.Text__c}" /></td> <td><apex:commandButton id="btn" value="click" onclick="refValue('{!index}')"/></td> <apex:variable var="index" value="{!VALUE(index)+1}"/> </tr> </apex:repeat> </table> </apex:form> <script type="text/javascript"> function refValue(val) { alert(document.getElementById('pg:frm:rpt:' + val + ':txt').value); } </script> </apex:page> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * Controllerクラス. */ public class LoopSampleController { public List<Sample__c> sampleList{get; set;} /** * コンストラクタ. */ public LoopSampleController() { this.sampleList = new List<Sample__c>(); for (Integer i = 0; i < 5; i++) { Sample__c sample = new Sample__c(); this.sampleList.add(sample); } } } |
ボタンがクリックされたら、その行のテキスト入力値をアラートで表示するというサンプルです。
行番号の取得の仕方はこの過去記事で書いてます。
【Visualforce+Apex】テーブルに連番を表示するサンプル
Javascriptへの値の渡し方はこの過去記事で書いてます。
【Apex+Visualforce】Javascriptに値を渡す簡単な書き方。apex:PageBlockTableやapex:repeat。
では、実際に動かしてみます。


想定とおり動きました。
コメント