How can I create a “link” to input particular keyw

2019-08-30 07:29发布

I'm working on Rails application.
If you click on that button, it automatically input @keyword into body_input
I want it with link_to instead of button_to.
How can I?

View

<%= button_to "Populate the chat box", "#name", :id => :username, :value => @keyword %>

jQuery

$(document).ready(function(e) {
     $('button#username').click(function () {
         e.preventDefault();
         $(".chat_input#body_input").val($(this).attr('value'));
     });
});

Additional Info(This is output javascript in HTML)

<script type="text/javascript">
    //<![CDATA[     
        $(document).ready(function(e) {
             $('button#username').click(function () {
                 e.preventDefault();
                 $(".chat_input#body_input").val($(this).attr('value'));
             });
        });
    //]]>
</script>

2条回答
时光不老,我们不散
2楼-- · 2019-08-30 08:15

I am not familiar wit ROR syntax but try this:

<%= link_to "Populate the chat box", "#name", :id => :username, :value => @keyword %>

and (Id must be unique so in the jquery selector on ID refrain from using tagname#Id just use ID)

$(document).ready(function(e) {  
     $('#username').click(function () {  
         e.preventDefault();
         $(".chat_input#body_input").val($(this).attr('value'));
     });
});
查看更多
何必那么认真
3楼-- · 2019-08-30 08:20

The following two are equivalent in function, though not in markup:

<%= link_to "Populate the chat box", "#name", :id => :username, :value => @keyword %>
<%= button_to "Populate the chat box", "#name", :id => :username, :value => @keyword %>

As commenter PSL astutely points out, if you decide to utilize a link_to to jump to a named anchor, you'll need to modify your jQuery function to remove e.preventDefault():

$(document).ready(function() {
     $('a#username').click(function () {
         $(".chat_input#body_input").val($(this).attr('value'));
     });
});
查看更多
登录 后发表回答