简体   繁体   中英

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. I can use javascript, jquery and/or regex here.

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).

 $("#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> 

Automatically responding to user input

In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input event.

 $("#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 the value of the input box and filter out , and check the length of it

 $('.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); } ) /

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM