假设具有类"store_edit"和id"store_edit_4"的表单以及字段store.description
是否有一种直接的方法在rails 3中添加字符计数器,因为他们已经删除了方便的field_observer?
只想让计数器随着他们输入的每个字符而增加......
我在几个博客中尝试了几种方法,但无济于事.这个是一个简单但有点傻,在输入框中显示字数而不是填充div标签,但即使我无法使用相同的字段名称等工作.例如,我把它放在我的(以前是空的)application.js:
$(document).ready(function(){
var code = document.code_search.search;
var remaining = document.code_search.remLen1;
function textCounting(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// Set the value
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
$('#test').keydown(function(){textCounting(code, remaining, 5)});
$('#test').keyup(function(){textCounting(code, remaining, 5)});
});
Run Code Online (Sandbox Code Playgroud)
将这个haml添加到我的所有常规内容之上(只是为了测试它与博客中相同的字段名称等)
= form_tag store_path, :method => 'get', :id => "code_search", :name => "code_search" do
%p
= text_field_tag :search, params[:search], :size => '5', :id => 'test'
%input{:maxlength => "3", :name => "remLen1", :readonly => "", :size => "3", :type => "text", :value => "5"}
characters left
Run Code Online (Sandbox Code Playgroud)
我的身体标签正下方的html看起来像这样:
<form accept-charset="UTF-8" action="/stores/AHPGKIUA" id="code_search" method="get" name="code_search"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<p>
<input id="test" name="search" size="5" type="text" />
<input maxlength='3' name='remLen1' readonly='' size='3' type='text' value='5'>
characters left
</input>
</p>
</form>
Run Code Online (Sandbox Code Playgroud)
我的HTML头部确实包含了application.js
然后我重新启动了webrick,将我的浏览器缓存...
但是当我输入字段时,计数的字符数不会改变.
在Rails 3中添加基本字符计数有一些相当直接的方法吗?
假设您正在使用jQuery和Haml(我假设您是基于您的问题),这是一个工作示例:
= text_field_tag :search, params[:search], :size => 5, :id => 'test'
%br
%span#char_count 140 characters left
:javascript
// just a function to pluralize the word "characters" based on the number
function pluralize_characters(num) {
if(num == 1) {
return num + " character";
} else {
return num + " characters";
}
}
$("#test").keyup(function() {
var chars = $("#test").val().length;
var left = 140 - chars; // sub 140 for your max length
if(left >= 0) {
$("#char_count").text(pluralize_characters(left) + " left");
} else {
left = left * (-1)
$("#char_count").text(pluralize_characters(left) + " too long");
}
});
Run Code Online (Sandbox Code Playgroud)
基于此代码.
| 归档时间: |
|
| 查看次数: |
1287 次 |
| 最近记录: |