jQuery 如何自动格式化文本框输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19709559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to auto format textbox inputs
提问by Ghost
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
</td>
</tr>
Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age. The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.
好吧,我的代码正在运行,但我希望我的“输入类型文本”像日期一样自动格式化(html 5 输入类型=日期),因为在我的 Servlet 中我将它转换为年龄。问题是,如果我使用“输入类型=日期”转换是错误的,所以我决定使用“输入类型=文本”并且它正在工作。那么是否可以在这种格式“mm/dd/yyyy”中自动放置“/”?例如,如果用户输入 2 个字符,“/”将自动输入等。
Servlet for birthdate to Age
用于从生日到年龄的 Servlet
String birthdate = request.getParameter("birthdate");
int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
int yearDOB = Integer.parseInt(birthdate.substring(6, 10));
DateFormat dateFormat = new SimpleDateFormat("MM");
java.util.Date date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("dd");
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("YYYY");
date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
int calAge = thisYear - yearDOB;
if (thisMonth < monthDOB) {
calAge = calAge - 1;
}
if (thisMonth == monthDOB && thisDay < dayDOB) {
calAge = calAge - 1;
}
String age = Integer.toString(calAge);
Update in the form
在表格中更新
<tr>
<td><label for="inputName">Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10" />
</td>
</tr>
Update in the source
在源中更新
<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>
Added Script
添加脚本
<script>
$('#input_date').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
</script>
I also tried the javascript but it's not working...
我也试过 javascript 但它不起作用......
回答by scunliffe
I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js
http://firstopinion.github.io/formatter.js/demos.htmlThis might be just the thing you're looking for.
我一直在 GitHub 上观看一个项目(并提供反馈以改进它),用于称为formatter.js
http://firstopinion.github.io/formatter.js/demos.html 的这种格式,这可能正是您想要的寻找。
This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.
这不会阻止您输入像 5 月 53 日这样的日期……但它会帮助您格式化。
new Formatter(document.getElementById('date-input'), {
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
or
或者
$('#date-input').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
回答by scunliffe
use datepicker api from jquery here is the link Datepicker
使用 jquery 中的 datepicker api 是链接Datepicker
and here is the working code
这是工作代码
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
</td>
</tr>
<script>
$(function() {
$( "#birthdate" ).datepicker();
});
</script>
EDIT
编辑
$("input[name='birthdate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
this is the code that you may need
这是您可能需要的代码
here is the fiddled code
这是修改后的代码
回答by Adam Leggett
I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup
and change
events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.
我有一个与 jquery-ui datepicker 一起使用的替代方法,没有 formatter.js。它旨在从keyup
和change
事件中调用。它添加了零填充。它通过从 dateFormat 字符串构造表达式来处理各种受支持的日期格式。我想不出用少于三个替换的方法来做到这一点。
// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\s*()\W*()?\W*()?([0-9]*).*")
.replace(/mm|dd/g, "\d{2}")
.replace(/yy/g, "\d{4}"));
var replace = "//"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, ""); // remove repeats
}
回答by Matthew D Auld
user2897690had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.
user2897690有正确的想法,但它不接受 Numpad 数字。所以拿了他们的 javascript 并修改了它来工作。
Here is my interpretation of their code with the added feature.
这是我对具有附加功能的代码的解释。
$("input[name='birthdate']:first").keyup(function(e){
var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
var key=chars.indexOf(e.keyCode);
console.log(key);
if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});