Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format with onchange

Tags:

javascript

I have many difficulties in doing this kind of formatting in the field. I have a form field:

<div class="form-group col-md-12 col-sm-12 col-xs-12">        
    <div class="col-md-2 col-sm-2 col-xs-2 form-label">
        {{Form::label('data', 'Data')}}
    </div>         
    <div class="col-md-10 col-sm-10 col-xs-10">            
        {{Form::date('data', null, ['class' => 'form-control'])}}
    </div>     
</div>

The intention is to make this field be in the following format, when a person enters 2 numbers the field automatically places a " / " forming the following type " 2 / 2 / 4 " insofar as the person is typing. However there is a detail, field allows the use of the backspace key but this will not compromise the automatic use of " / ".

I tried to do as the other topics but did not have success...

like image 723
Lincoln Binda Avatar asked May 04 '16 20:05

Lincoln Binda


1 Answers

You can use regex to this work. Check text format using match().

var lastValue = $("input").val();
$("input").on("keydown keyup change", function(){
    var value = $(this).val();
    if (value.match(/^[0-9]*[\/]?[0-9]*[\/]?[0-9]*$/g))
        lastValue = value;
    else
        $(this).val(lastValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
like image 66
Mohammad Avatar answered Sep 22 '22 14:09

Mohammad