2011-01-22 8 views
0

私は次の問題があります。多くのビジネスルールが存在するので、これらの関数をjsとして自動的に更新することに決めました。私は持っている私の見解でJavaScriptは操作のための値を取得できません

: これはテーブル

(<%= javascript_include_tag 'people'%>) 

     <th>Name</th> 
     <th>Money</th> 
     <th>Money Comment</th> 
    </tr> 
    <% @counter = 0 %> 
    <% @people.each do |p| %> 
    <% @counter += 1 %> 
    <tr> 
    <%= form_for(:p) do |f| %> 
    <th><%= f.label(p.name) %></th> 
    <th><label for="<%= "money_" + @counter.to_s %>"> <%= f.select(:money, 1..10, :selected => p.money)%></label></th> 
    <th><label for="<%= "comment_" + @counter.to_s %>"> <%= f.label(p.money_comment, :disabled => 'disabled')%></label></th> 
    <% end %> 
    <% end %> 

と機能は次のようになりますJavaScriptで内部にある:

function change_people() { 
    money1 = $('money_1').getValue(); 
    if (money1 == 10) { 
    $('comment_2').setValue("I know what you're doing you mofo"); 
    } 
    else { 
    $('comment_2').setValue(""); 
    } 
} 

document.observe('dom:loaded', function() { 
    change_people(); 
    $('money_1').observe('change', change_people); 
}); 

が、それは、それはdoesnの私に言って続けて何らかの理由私は "money_1"の意味を理解していません。私はhtmlソースをチェックし、ビューをコンパイルしていますが、jsで要素を間違って参照していますか?

ありがとうございました!

+0

({})あなたが含まれたコードのためのエディタでコードのマークアップを使用してください。 –

答えて

0

それはあなたがセレクタ必要かのように見えます:

<th id="<%= "money_" + @counter.to_s %>"> 
<label for="<%= "money_" + @counter.to_s %>"> 
    <%= f.select(:money, 1..10, :selected => p.money)%> 
</label> 
</th> 

を今、あなたはどのあなたは、プロトタイプに正しい要素(あなたが探している値の選択)を検索し、発見する能力を与えてくれましたgetValue()を呼び出すために$()関数に渡す:

function change_people() { 
    // Note the "#" on #money_1, which is an ID selector 
    // the space " " between is a descendant element selector 
    money1 = $($$('#money_1 select')).getValue(); 
    if (money1 == 10) { 
     // do stuff 
    } else { 
     // do other stuff 
    } 
} 

あなたは、テーブル内のお金の選択のすべての値を反復処理するために探している場合は、あなたの代わりにクラスを使用したいと思います。 IDごとに1つの要素しか持つことはできませんが、ルールごとのクラスは属性ごとにグループ化されます。違いは次のようになります。

あなたのJavaScriptで
<th class="money_select"> 
<label for="<%= "money_" + @counter.to_s %>"> 
    <%= f.select(:money, 1..10, :selected => p.money)%> 
</label> 
</th> 

そして:

function change_people() { 
    // Note the "." on .money_1, which is a class selector 
    // the space " " between is a descendant element selector 
    $$('.money_select select').each(function(element){ 
     if ($(element).getValue() == 10) { 
      // do stuff 
     } else { 
      // do other stuff 
     } 
    }); 
} 
+0

ありがとうJaredさん、ちょうどこれをjsに追加しようとしましたが、同じエラーが表示されました。今は、それは私に間違っていると言うことの名前を変更しました。 money1 = $( '#money_1')。getValue(); Uncaught TypeError:nullのメソッド 'getValue'を呼び出すことはできません – Lievcin

+0

@Lievcin:編集を参照してください。 –

+0

@Lievcin:また、ソースHTMLを投稿することができれば、ブラウザはルビコードの代わりに見ています。 –

関連する問題