erikhh92 erikhh92 - 24 days ago 7
Javascript Question

Same function to any numbers of inputs elements javascript

i have multiple elements like this:

<input type="text">


And i want to apply / on this input to enter date format. I am using the next function, but only applies on ID.. i want to apply the function on every input with date format.

$(document).ready(function() {
$("#fecha").keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});


Any help?

Answer

Select all input type="text" elements within parent element where keyup event handler should be called on. You can alternatively set a common .className at the elements and use .className selector $(".date")

$(document).ready(function() {
  $("#form input[type=text]").keyup(function() {
    if (this.value.length == 2) {
      $(this).val(this.value + "/");
    } else if (this.value.length == 5) {
      $(this).val(this.value + "/");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form id="form">
  <input type="text" />
  <input type="text" />
</form>