簡體   English   中英

如何使用javascript或jquery計算文本框中的逗號數?

[英]How to count the number of commas in a text box using javascript or jquery?

單擊提交按鈕后,我想進行一些客戶端驗證,以確保文本框中的submit-btn類少於五個逗號。 我可以在這里使用javascript,jquery和/或regex。

我應該在該函數中放置什么代碼?

$('.submit-btn').on("click", function() {
  << WHAT GOES HERE? >>
});

任何幫助是極大的贊賞。

我用正則表達式來發現的次數字符串,出現在文本框的值。 打印是否有效(少於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> 

自動響應用戶輸入

在這種特殊情況下,我希望進行實時驗證。 這可以通過使用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">&nbsp;</div> 

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> 

您可以嘗試使用此逗號計數器

$('button').on('click',function(){ var counter = ($('div').html().match(/,/g) || []).length; $('.result').text(counter); } ) /

您也可以刪除所有不是逗號[^,] ,將其替換為空字符串並計算字符串的長度。

 $('.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM