Tony M
Tony M

Reputation: 341

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.

Upvotes: 0

Views: 1585

Answers (4)

The fourth bird
The fourth bird

Reputation: 163362

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>

Upvotes: 1

Neil
Neil

Reputation: 14313

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>

Upvotes: 4

Rani Moreles Rubillos
Rani Moreles Rubillos

Reputation: 1108

You could try using this Comma Counter

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

Upvotes: 1

brk
brk

Reputation: 50316

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>

Upvotes: 3

Related Questions