【问题标题】:Adding text on button click to simple form with jquery使用 jquery 在按钮单击上添加文本到简单表单
【发布时间】:2017-01-26 07:07:11
【问题描述】:

我开始使用 jQuery,我正在尝试添加引导按钮,以便在单击时将西班牙重音元音添加到 simple_form 文本字段。我在回答this 问题后对代码进行了建模,但是在单击按钮时目前没有任何反应——我做错了什么吗?

在视图中,我使用了简单的表单并在文本字段中添加了一个包装器 id:

<%= simple_form_for @word, url: lesson_image_spelling_path(current_lesson, @word.word), method: :patch do |f| %>
    <%= f.input :spelling_attempt, wrapper_html: { id: 'txt' }, label: "Spell the word:" %>

    <br>

    <button type="button" class="btn btn-secondary btn-sm" id="a-accent">á</button>

    <%= f.button :submit, "Submit", class: 'btn btn-primary' %>
<% end %>

在 application.js 我有:

jQuery("#a-accent").on('click', function() {
  var $txt = jQuery("#txt");
  var caretPos = $txt[0].selectionStart;
  var textAreaTxt = $txt.val();
  var txtToAdd = "test";
  $txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});

【问题讨论】:

  • 将您的 jquery 包装在 document.ready(function(){...}) 中,或者将 click 事件处理程序附加到全局 $(document).on('click','#a-accent', function(){..})

标签: javascript jquery ruby-on-rails twitter-bootstrap simple-form


【解决方案1】:

也许使用 input_html 而不是 wrapper_html。 将 console.log('btn clicked') 放入您的点击事件中,如果此事件有效,请查看浏览器控制台。

【讨论】:

  • Rik 建议的 input_html 加上 document.ready(function) 的组合成功了 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
相关资源
最近更新 更多