帮助我在插入时在文本框字段中设置信用卡号码格式1111-1111-1111-1111。
<div class="form-group">
<label>Card Number</label>
<input type="text" class="form-control" placeholder="xxxx-xxxx-xxxx-xxxx" name="card-number" id="credit-card" value="" >
</div>
<div class="form-group center-block">
<input type="button" name="btn-update" id="btn-update" value="UPDATE" class="btn">
</div>
答案 0 :(得分:4)
如果您使用的是jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="creditCardText" value="1234-1234-1234-1234" />
{{1}}
答案 1 :(得分:1)
使用onkeyup Event
,您可以跟踪用户输入的字符数。
function formatCreditCard() {
var x = document.getElementById("credit-card");
var index = x.value.lastIndexOf('-');
var test = x.value.substr(index + 1);
if (test.length === 4)
x.value = x.value + '-';
}
<div class="form-group">
<label>Card Number</label>
<input type="text" class="form-control" onkeyup="formatCreditCard()" placeholder="xxxx-xxxx-xxxx-xxxx" name="card-number" id="credit-card" value="" >
</div>
<div class="form-group center-block">
<input type="button" name="btn-update" id="btn-update" value="UPDATE" class="btn">
</div>
答案 2 :(得分:1)
您可以拥有自己的自定义逻辑:
$('input[name=card-number]').keypress(function(){
var rawNumbers = $(this).val().replace(/-/g,'');
var cardLength = rawNumbers.length;
if(cardLength !==0 && cardLength <=12 && cardLength % 4 == 0){
$(this).val($(this).val()+'-');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Card Number</label>
<input type="text" class="form-control" placeholder="xxxx-xxxx-xxxx-xxxx" name="card-number" id="credit-card" value="" maxlength="19" >
</div>
<div class="form-group center-block">
<input type="button" name="btn-update" id="btn-update" value="UPDATE" class="btn">
</div>
&#13;
答案 3 :(得分:0)
<div class="tagsList">
<ul>
<li><a href="linksmth"><span class="tagSpan">Tag name here</span></a></li>
</ul>
</div>
<a class="with-margin" href="linksmth"><span class="tagSpan">Tag name here</span></a>
HTML代码
var txtCardNumber = document.querySelector("#txtCardNumber");
txtCardNumber.addEventListener("input", onChangeTxtCardNumber);
function onChangeTxtCardNumber(e) {
var cardNumber = txtCardNumber.value;
// Do not allow users to write invalid characters
var formattedCardNumber = cardNumber.replace(/[^\d]/g, "");
formattedCardNumber = formattedCardNumber.substring(0, 16);
// Split the card number is groups of 4
var cardNumberSections = formattedCardNumber.match(/\d{1,4}/g);
if (cardNumberSections !== null) {
formattedCardNumber = cardNumberSections.join('-');
}
console.log("'"+ cardNumber + "' to '" + formattedCardNumber + "'");
// If the formmattedCardNumber is different to what is shown, change the value
if (cardNumber !== formattedCardNumber) {
txtCardNumber.value = formattedCardNumber;
}
}
答案 4 :(得分:0)
试试这个,
var newText = myText.Replace(@"\\", @"\");