Add CSS class in Input when Loading page

Asked

Viewed 1,161 times

0

I want to add class="cpf_cnpj" in a input id input-custom-field2 when loading the page, follow the html and javascript I tried to use but without success:

<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>

2 answers

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>
<input type="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">

1


I was mixing native javascript methods (document.getElementById) with jquery methods (addClass), so did not do what expected. These two methods return different things. Do so:

$(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>
<input type="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">

  • I tried to use the same idea doing this but I couldn’t, doesn’t add the class to the label: See here.

  • @Wendell is there because it is not importing jquery: it should import before using it, so for example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>, before all your JS (javascript). Anyway there is another example where you don’t need jquery

  • I use Opencart, it already has the library included. See the page here, the field is the input CPF

  • @Wendell class is being added correctly: https://postimg.org/image/jf871fc1n/ . As you can see there, the element is in the class

  • Yes I saw and thank you for your help, I just couldn’t do the same label right below where I want to display a div saying that the field is mandatory.

  • @Wendell if it is on the label that you want the class then select the label: $('label[for="input-custom-field2"]').addClass('...')

Show 1 more comment

Browser other questions tagged

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