Add CSS class to Input while loading page

0

I want to add class="cpf_cnpj" to a input with id input-custom-field2 when loading the page, follow the html and javascript that I tried to use but to no avail:

<input type="text" name="custom_field[account][2]" value="" placeholder="CPF" id="input-custom-field2" class="form-control">

<script>
    $(document).ready(function() {
        document.getElementById("input-custom-field2").addClass('cpf_cnpj');
    });
</script>
    
asked by anonymous 08.08.2016 / 14:53

2 answers

1

I was mixing native javascript methods ( document.getElementById ) with jquery methods ( addClass ), so I was not expecting it. These two methods return different things. Here's how:

$(document).ready(function() {
    $("#input-custom-field2").addClass('cpf_cnpj');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" name="custom_field[account][2]" value="" placeholder="CPF" id="input-custom-field2" class="form-control">

To do with native javascript:

var input = document.getElementById("input-custom-field2");
input.className += " cpf_cnpj";
<input type="text" name="custom_field[account][2]" value="" placeholder="CPF" id="input-custom-field2" class="form-control">
    
08.08.2016 / 14:57
1

You can solve your problem like this:

Jquery

$(function(){
   $("#input-custom-field2").addClass('cpf_cnpj');
});
.cpf_cnpj{border-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text" name="custom_field[account][2]" value="" placeholder="CPF" id="input-custom-field2" class="form-control">

JavaScript

document.getElementById("input-custom-field2").className = 'cpf_cnpj';
.cpf_cnpj{border-color:red;}
<input type="text" name="custom_field[account][2]" value="" placeholder="CPF" id="input-custom-field2" class="form-control">
    
08.08.2016 / 14:57