2014-10-09 36 views
1

我是Rails和HTML5的新手。 我想用Jquery制作更时尚的表单。 它的代码就在这里:有没有办法用<textarea>取代f.text_area?

查看:

<textarea name="styled-textarea" id="styled" onfocus="this.value=''; setbg('#e5fff3');" onblur="setbg('white')">Enter your comment here... </textarea> 

JS:

function setbg(color) 
{ 
document.getElementById("styled").style.background=color 
} 

这textarea的应该属于这种形式:

<%= form_for([@post, @post.comments.build]) do |f| %> 
    <%= f.label :commenter %><br /> 
    <%= f.text_field :commenter %><br /><br /> 
    <%= f.text_area :body %> 
    <%= f.submit %><br /> 
<% end %> 

我想更换<%= f.text_area :body %><textarea>能够使用jquery但t他不保存我的评论(显然)。我错过了什么,或者这是不可能的?有没有其他的方式来使用jQuery与<%= f.text_area :body %>,也许插入一个div内?

任何帮助将非常感激! :)

回答

1

您可以设置自定义ID为您的表单域,就像这样:

<%= f.text_area :body, id: 'styled' %> 

jQuery的

$("#styled").on('focus', function(){ 
    $(this).val(''); 
    setbg('#e5fff3'); 
}); 

$("#styled").on('blur', function(){ 
    setbg('white') 
}); 

而不是jQuery的,是更好地利用CSS

#styled:focus { 
    background: #e5fff3; 
} 

#styled { 
    background: white; 
} 
0

请不要使用内联JS! 但使用jQuery和保持实际f.text_area,做这样的事情:

<script> 
    $('youtextarea_id') 
    .on('focus', function() { 
    $(this).val(''); 
    setbg('#e5fff3'); 
    } 
    .on('blur', function() { 
    setbg('white'); 
    }; 
</script> 

由轨道生成的ID,你可以看到它在生成的HTML。你可以随时更改它f.text_area :body, id: 'another_id'

+0

我用CSS代替。无论如何感谢您的帮助!:) – 2014-10-09 15:34:00