Search code examples
javascriptjqueryruby-on-railstwitter-bootstrapsimple-form

Adding text on button click to simple form with jquery


I'm starting out with jQuery, and I'm trying to add bootstrap buttons that add Spanish-accent vowels to the simple_form text field on click. I'm modeled the code after an answer to this question, but nothing is currently happening upon clicking the button--am I doing something wrong?

In the view, I'm using simple form and adding a wrapper id to the text field:

<%= 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 %>

In application.js I have:

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) );
});

Solution

  • Maybe use input_html instead of wrapper_html. Put console.log('btn clicked') into your click event and look in browser console if this event work.