2

This is my HTML

<input type="text" class="date_of_birth" name="date[]" value="" onkeyup="dateOfBirth('stepbirth')">
<input type="text" class="date_of_birth" name="date[]" value="" onkeyup="dateOfBirth('stepbirth')">

Here is my javascript to collect the value for each element.

var DoB = []; 
  $(".date_of_birth").each(function(){
      DoB.push($(this).val());
  });

  var newDob = DoB.slice(0,-1);

  var stepVar = newDob;

It is working fine. When there are more values it sends values like this

20/02/2002,03/03/2003

which is fine.But the issue i have event on keyup on each input field. When the user fill in both fields and after if remove the data from one field then it sends values like this..

20/02/2002,

So my script stops validation here because of comma it expect the values like

20/02/2002,03/03/2003 

or

20/02/2002

How can i remove comma here until input is empty.

Thanks

2 Answers 2

2

Instead of removing the commas, fix the problem at the source. The cause is due to the fact that you always push the value to the array even if the value is empty. To fix this, check the value before calling push().

var DoB = []; 
$(".date_of_birth").each(function() {
  var value = $(this).val().trim();
  if (value.length)
    DoB.push($(this).val());
});

Alternatively you can make this more succinct by using map(). If you return null, then the element will not be added to the array.

var DoB = $(".date_of_birth").map(function() {
  return $(this).val().trim() || null;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please help me with this thread.. stackoverflow.com/questions/57306556/…
0

You can use "toArray" and filter all elements with values:

 var DoB = $(".date_of_birth").toArray().filter(function(el) {return $(el).val().trim();});

or using arrow function

var DoB = $(".date_of_birth").toArray().filter(el => $(el).val().trim());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.