[英]How can I make it automatically input particular keyword into text field when a user click a button?
I have a HTML form. 我有一个HTML表单。 I'd like to add a button, with which a particular keyword will be automatically input into certain input field(Just like Twitter's reply) 我想添加一个按钮,通过该按钮可以将特定的关键字自动输入到某些输入字段中(就像Twitter的回复一样)
Then it also jump to certain link. 然后它也跳到某些链接。
How can I implement that with jQuery or Javascript? 如何使用jQuery或Javascript实现该功能?
HTML(Form part) HTML(表单部分)
<a name="comment_part"></a>
<form accept-charset="UTF-8" action="/users/John/comments" class="new_comment" data-remote="true" enctype="multipart/form-data" id="new_comment" method="post">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="vvwHbqyiDXv0Sv5NrbPP5kfdwhovbHkkOUm2/2uJdNs=" />
<input class="chat_input" id="body_input" name="comment[body]" type="text" />
<button type="submit" class="btn">Submit</button>
</form>
HTML(Button part) HTML(按钮部分)
keyword = "@John "
(here, I want to show a button. If a user click on it, `@John ` will be automatically input into the input field above `input class="chat_box" id="body_input"` then jump to a link `<a name="comment_part"></a>`)
How can I archive this with jQuery or Javascript? 如何使用jQuery或Javascript存档?
Create a button and assign it a unique id
attribute: 创建一个按钮并为其分配一个唯一的id
属性:
<button type="button" id="username" value="#{@keyword}">Populate the chat box</button>
Then, in jQuery, listen for a click on that button; 然后,在jQuery中,侦听该按钮的单击; when it's clicked, pass the value
attribute and assign it to input.chat_input#body_input
: 单击它时,传递value
属性并将其分配给input.chat_input#body_input
:
$(document).ready(function(e) {
$('button#username').click(function () {
e.preventDefault();
$(".chat_input#body_input").val($(this).attr('value'));
});
});
EDIT: 编辑:
If instead you want the button click to jump to a name link, you can use Rails' button_to
helper : 相反,如果您希望按钮单击跳转到名称链接,则可以使用Rails的button_to
helper :
<%= button_to "Populate the chat box", "#name", :id => :username, :value => @keyword %>
Depending on where that keyword is coming from, just attach it to your button as a data attribute... 根据该关键字的来源,只需将其作为数据属性附加到您的按钮即可...
<button class='yourbutton' data-keyword="@john">YOUR BUTTON</button>
Then the Jquery, goes inside your document ready code... 然后,Jquery进入文档准备好的代码...
$('.yourbutton').click(function(e){
e.preventDefault();
$('#body_input').val($(this).data('keyword'));
$('html, body').animate({scrollTop: $('a[name="comment_part"]').offset().top -100 }, 'slow');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.