使用 jquery 在按钮单击上添加文本到简单表单

Posted

技术标签:

【中文标题】使用 jquery 在按钮单击上添加文本到简单表单【英文标题】:Adding text on button click to simple form with 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()..) 【参考方案1】:

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

【讨论】:

Rik 建议的 input_html 加上 document.ready(function) 的组合成功了 :)

以上是关于使用 jquery 在按钮单击上添加文本到简单表单的主要内容,如果未能解决你的问题,请参考以下文章

使用 jQuery 在按钮单击上添加声音

动态添加字段到 laravel 表单

如果单击任何表单元素,则使用 Jquery 启用提交按钮

jQuery将文本字段的值附加到表单提交列表中

在按钮上单击js添加项目到列表

Jquery Button 使表单可见