Martin Smith
Martin Smith

Reputation: 61

Counting how many comma seperated strings in an input

How do I display the number of comma seperated data in a input box?

Example: Input box: 2015-01-01, 2015-01-02, 2015-01-03 I want the output to another box saying 3 because there are 3 dates selected.

I tried something like:

var vacDays = $('#vacationDays').val().split(",");
for (i=0; i < vacDays.length; i++) {
    $('#vacationDaysTaken').val(vacDays[i]);
}

But this only displays the last date for some reason?

I also tried:

var vacDays = $('#vacationDays').split(",");
$('#vacationDaysTaken').val(vacDays);

but this doesn't do anything for me.

Lastly I tried:

var vacDays = $('#vacationDays').length;
$('#vacationDaysTaken').val(vacDays);

But this only outputs 1.

Any help would be great. Thanks again!

Upvotes: 2

Views: 1471

Answers (3)

william.taylor.09
william.taylor.09

Reputation: 2215

You were close with this:

var vacDays = $('#vacationDays').split(",");
$('#vacationDaysTaken').val(vacDays);

Should instead be this:

var vacDays = $('#vacationDays').val().split(",").length;
$('#vacationDaysTaken').val(vacDays);

Upvotes: 2

John williams
John williams

Reputation: 731

Just count the array element that split() returns using the length property

var vacDays = $('#vacationDays').val().split(",");
var commaCount = vacDays.length;

Upvotes: 0

Srinath Mandava
Srinath Mandava

Reputation: 3462

This would display the number of comma separated strings

var vacDays = $('#vacationDays').val().split(",").length;
 $('#vacationDaysTaken').val(vacDays);

Upvotes: 4

Related Questions