1

簡単な形式で:

<%= form_for @user do |f| %>
  <%= f.label :source, "How did you find out about us?", :class => "control-label" %>
  <%= f.select(:source, options_for_select([['--  Please select  --',nil],['Source 1','Source 1'], ['Source 2','Source 2'], ['Other','Other']])) %>

  <%= f.label :source_other, "Specify Other Source" %>
  <%= f.text_field :source_other %>
<% end %>

「source」フィールドから値「Other」が選択されたときに、JQuery を使用して「source_other」テキスト フィールドのみを表示する方法を学習しようとしています。オンラインで見たところ、次のようなものを使用する必要があるようです。

$("#source").change(function() {
  if ($("#source").val()=="Other")
    $("#source_other").show();
  else
    $("#source_other").hide();
});

ただし、JQuery をフォームに統合する方法がよくわかりません。誰かが私を正しい方向に向けてもらえますか?

更新しました:

結果の html スニペットは次のとおりです。

<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post">
  <label class="control-label" for="user_lead_source">How did you find out about us?</label>
  <select id="user_source" name="user[source]"><option value="">--  Please select  --</option>
    <option value="Source 1">Source 1</option>
    <option value="Source 2">Source 2</option>
    <option value="Other">Other</option>
  </select>

  <label for="user_source_other">Specify Other Source</label>
  <input id="user_source_other" name="user[source_other]" size="30" type="text" />
</form>
4

4 に答える 4

2

サーバー コードが要素の ID を生成していないのではないかと疑っています。その場合、セレクターは存在しない ID を持つ要素を探しています。

その場合は、サーバー コードに ID を追加して jQuery ID セレクターが機能するようにするか、name=セレクターを使用します。

$(function(){
    $('input[name="source"]').change(function() {
      $('input[name="source_other"]').toggle(  $(this).val()=="Other" );

    });
});

jQuery コードがラップされている$(document).ready()$(function(){});、same の省略形である限り、jQuery ライブラリがロードされた後であれば、スクリプト タグ内のページのどこにでも配置できます。または、jQuery の後にロードされる外部ファイルに配置することもできます

于 2012-12-18T00:03:43.220 に答える
1

交換

 $("#source") with $("#user_source")
于 2012-12-19T10:56:05.230 に答える
0

$("#user_source")代わりにあるはずです!

Rails は属性の前にモデル名を追加します。次に、$("#user_source_other")要素を非表示/表示する必要があります。

さらに、この jQuery JS コードを charlietflで、$(document).ready()または前に回答したようにラップする必要があります。$(function(){});

于 2012-12-18T15:31:44.470 に答える