Add class in Javascript?

Asked

Viewed 39 times

-4

I need the code below to work via class and not via function is like this:

<input oninput="mascara(this)" type="text">

and I need it to work via class, thus:

<input class="minhafuncao" type="text">

how to change the code below:

<input oninput="mascara(this)" type="text">
<script type="text/javascript">
    function mascara(i){       
        var v = i.value;   
        if(isNaN(v[v.length-1])){
            i.value = v.substring(0, v.length-1);
            return;
        }   
        i.setAttribute("maxlength", "14");
        if (v.length == 1 || v.length == 0) 
            i.value += ".";
        if (v.length == 11) 
        i.value += "-";
    }
</script>
  • 1

    It doesn’t make sense for me to ask you. It’s like you want to use a javascript class as an attribute HTML class, is a mistake. Maybe you didn’t understand, could clarify?

  • 1

    Ola Cario, please take a [tour] around the platform to learn more about how to formulate your question. Here in the SO we help people to solve problems, what you ask is for someone to do their work by Oce, please put what your doubt and also put the code that Oce already tried and it did not work.

  • So I understand perfectly. Thank you

1 answer

0

Hello, from what I understand you want instead of using a direct function in the element, create an event through the class.

<input class="minhafuncao" type="text">
<script type="text/javascript">
    $('.minhafuncao').on('change', function() {
        var v = this.value;   
        if(isNaN(v[v.length-1])){
            i.value = v.substring(0, v.length-1);
            return;
        }   
        i.setAttribute("maxlength", "14");
        if (v.length == 1 || v.length == 0) 
            i.value += ".";
        if (v.length == 11) 
        i.value += "-";
    });
</script>

I didn’t mind the code you executed, but the way you can perform functions through a selector. Follow the documentation link for Jquery.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.