使用 jquery 将按钮上的文本添加到简单表单

Adding text on button click to simple form with jquery

我从 jQuery 开始,我正在尝试添加 bootstrap 按钮,这些按钮在单击时将西班牙口音元音添加到 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) );
});

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