简体   繁体   中英

calling a function for onkeyup event in javascript for input masking

I have a html code which will do the input masking for the date entry which is given below

<html>

<input
    type="text"
    name="date"
    placeholder="dd/mm/yyyy"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{2}$/) !== null) {
            this.value = v + '/';
        } 
        else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            this.value = v + '/';

        }

     "
    maxlength="10"
>
</html>


It takes the input in the specified format and this is working fine,, but I wanted to call this as a function and I tried this

<br><script type="text/javascript">

function check(t){
        var v = t;
        if (v.match(/^\d{2}$/) !== null) {
            t = v + '/';
        return;
        } 
        else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            t = v + '/';
        return;

    }
}

</script>
<html>


<input
    type="text"
    name="date" style="text-transform: uppercase";
    placeholder="dd/mm/yyyy"
    onkeyup="check(this.value);"
    maxlength="8"
>
</html>

but i didn't get the required result. it is taking the value as ,say 11111111 where it should have taken 11/11/1111
What may be wrong here?

You have to give like this , If you want to reflect the changes into textbox

function check(t){
          var v = t;

        if (v.match(/^\d{2}$/) !== null) {

            t = v + '/';
            document.getElementById("t1").value=t;
        return ;
        } 
        else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            t = v + '/';
            document.getElementById("t1").value=t;
        return ;

    }
}

working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM