[英]How to count the number of commas in a text box using javascript or jquery?
Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. 单击提交按钮后,我想进行一些客户端验证,以确保文本框中的submit-btn类少于五个逗号。 I can use javascript, jquery and/or regex here. 我可以在这里使用javascript,jquery和/或regex。
What code should I place within this function? 我应该在该函数中放置什么代码?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated. 任何帮助是极大的赞赏。
I use regex to find the number of times the string ,
occurs in the textbox value. 我用正则表达式来发现的次数字符串,
出现在文本框的值。 It prints whether or not it is valid (having less than 5 commas). 打印是否有效(少于5个逗号)。
$("#validate").click(function () { console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="textboxInfo" /> <button id="validate">less than 5 commas?</button>
In this particular situation, I'd prefer to have live validation. 在这种特殊情况下,我希望进行实时验证。 This can be accomplished by using the input
event. 这可以通过使用input
事件来完成。
$("#textboxInfo").on('input', function () { var isValid = ($(this).val().match(/,/g) || []).length < 5; $(".isValid").html(isValid ? "Valid" : "Invalid"); }).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="textboxInfo" value="I really love ,,, commas!" /> <div class="isValid"> </div>
Split
the value of the input box and filter
out ,
and check the length of it Split
输入框的值并filter
掉,
然后检查其长度
$('.submit-btn').on("click", function() { var getNumbers = $('#testBox').val().split('').filter(function(item) { return item === ',' }).length; console.log(getNumbers) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='testBox'> <button class='submit-btn' type="button">Click</button>
You could try using this Comma Counter 您可以尝试使用此逗号计数器
$('button').on('click',function(){ var counter = ($('div').html().match(/,/g) || []).length; $('.result').text(counter); } )
/ $('button').on('click',function(){ var counter = ($('div').html().match(/,/g) || []).length; $('.result').text(counter); } )
/
You could also remove everything that is not a comma [^,]
, replace that with an empty string and count the length of the string. 您也可以删除所有不是逗号[^,]
,将其替换为空字符串并计算字符串的长度。
$('.submit-btn').on("click", function() { var nr = $("#tbx").val().replace(/[^,]/g, "").length; console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas."); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='tbx'> <button class='submit-btn' type="button">Click</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.