Change placeholder checking radio with jquery

1

Hello, I'm trying to change the placeholder of an input by checking between 2 input radio values. Below is the js I tried to mount and the html.

$(document).ready(function () {
	$('#tipousuario').prop('checked',function () {                    
		if($(this).val() === '1'){
			$(this).attr({placeholder:"Insira seu CNPJ",maxlenght:"14"});
		}
		if($(this).val() ==='2'){
			$(this).attr({placeholder:"Insira seu CRC",maxlenght:"8"});
		}
	});
});
 <div class="col-lg-7">
    <div class="form-group">
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="tipouser" id="tipousuario" value="1" checked>
            <label class="form-check-label" for="inlineRadio1">CNPJ</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="tipouser" id="tipousuario" value="2">
            <label class="form-check-label" for="inlineRadio2">CRC</label>
        </div>
    </div>
    <div class="form-group">                                   
        <input type="text" required="required" class="form-control" maxlength="14" name="usuario" id="InputUsuario" pattern="[0-9]+$" placeholder="Usuário">                                    
        <small class="text-muted">Apenas números</small>
   </div>
    
asked by anonymous 09.04.2018 / 22:34

4 answers

2

Your logic makes sense, but there are some flaws in your code, come on:

  • At line $('#tipousuario').prop('checked', you actually need to apply the event to the element to catch when the value changes, then change to: $('.tipousuario').on('change', ;
  • In line $('#tipousuario') , since they are 2 radios, searching by ID can only take 1 element, since by definition each HTML document should not have elements with duplicate IDs, so I renamed the ID's to become unique and added the class user
  • At line $(this).attr({ , we actually need to change the attributes in the input text, then change to select by input ID: $('#InputUsuario')
  • Follow the settings below:

    $(document).ready(function () {
    	$('.tipousuario').on('change',function () {
    		if($(this).val() === '1'){
    			$('#InputUsuario').attr({placeholder:"Insira seu CNPJ",maxlength :"14"});
    		}
    		if($(this).val() ==='2'){
    			$('#InputUsuario').attr({placeholder:"Insira seu CRC",maxlength :"8"});
    		}
    	});
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-lg-7">
        <div class="form-group">
            <div class="form-check form-check-inline">
                <input class="form-check-input tipousuario" type="radio" name="tipouser" id="tipousuario1" value="1" checked>
                <label class="form-check-label" for="inlineRadio1">CNPJ</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input tipousuario" type="radio" name="tipouser" id="tipousuario2" value="2">
                <label class="form-check-label" for="inlineRadio2">CRC</label>
            </div>
        </div>
        <div class="form-group">                                   
            <input type="text" required="required" class="form-control" maxlength="14" name="usuario" id="InputUsuario" pattern="[0-9]+$" placeholder="Insira seu CNPJ">                                    
            <small class="text-muted">Apenas números</small>
       </div>
        
    09.04.2018 / 23:00
    1

    First of all you can not put the same id for two different elements, so I removed it from the element radio , and I used name to manipulate it.

    I added the change event, so I can get the status change of the radio element.

    Initialized placeholder with Insira seu CNPJ .

    And I removed $(this) in the part where the values are sent, this causes the attributes of radio to be changed and not input .

    Result:

    html (I just removed the ids repeated)

    <div class="col-lg-7">
        <div class="form-group">
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="tipouser" value="1" checked>
                <label class="form-check-label" for="inlineRadio1">CNPJ</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="tipouser" value="2">
                <label class="form-check-label" for="inlineRadio2">CRC</label>
            </div>
        </div>
        <div class="form-group">                                   
            <input type="text" required="required" class="form-control" maxlength="14" name="usuario" id="InputUsuario" pattern="[0-9]+$" placeholder="Usuário">                                    
            <small class="text-muted">Apenas números</small>
       </div>
    

    Jquery code:

    $(function () {
        var usuario = $('[name="usuario"]');
      var tipouser = $('[name="tipouser"]');
      usuario.attr({placeholder:"Insira seu CNPJ",maxlength:"14"});
        tipouser.change(function () {                    
            if($(this).val() === '1'){
                usuario.attr({placeholder:"Insira seu CNPJ",maxlength:"14"});
            }
            if($(this).val() ==='2'){
                usuario.attr({placeholder:"Insira seu CRC",maxlength:"8"});
            }
        });
    });
    

    Example: link

        
    09.04.2018 / 22:59
    1

    You can do this by using ternary , by clicking on the radios buttons by name="tipouser" .

      

    In addition to the error in% with duplicate% s, there was another error: instead of    id you were using maxlength (ending with maxlenght ).

    Code:

    $(document).ready(function () {
       $('[name="tipouser"]').click(function() {
          $('#InputUsuario').attr(
             $(this).val() === '1' ? // operador ternário
             { placeholder:"Insira seu CNPJ", maxlength:"14" } : // aqui se o valor for igual a 1
             { placeholder:"Insira seu CRC", maxlength:"8" } // aqui se o valor não for 1
          );
       });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-lg-7">
       <div class="form-group">
         <div class="form-check form-check-inline">
             <input class="form-check-input" type="radio" name="tipouser" id="tipousuario1" value="1" checked>
             <label class="form-check-label" for="inlineRadio1">CNPJ</label>
         </div>
         <div class="form-check form-check-inline">
             <input class="form-check-input" type="radio" name="tipouser" id="tipousuario2" value="2">
             <label class="form-check-label" for="inlineRadio2">CRC</label>
         </div>
       </div>
       <div class="form-group">                                   
         <input type="text" required="required" class="form-control" maxlength="14" name="usuario" id="InputUsuario" pattern="[0-9]+$" placeholder="Insira seu CNPJ">                                    
         <small class="text-muted">Apenas números</small>
       </div>
    </div>
        
    10.04.2018 / 00:14
    0

    id defines a unique identifier (ID) that must be unique throughout the document, so you can not repeat it.

    Instead of getting its input through id I'll get it by the name attribute.

    Another important point is that in your example the value of this depends on how the function is called. It references% changed%, that is, input .

    So when you say:

    $(this).attr({placeholder:"Insira seu CRC",maxlenght:"8"});
    

    You are modifying the attributes of <input type="radio" /> wrong.

    One more important point is that the name of the input attribute was wrong.

    Tip: Clear the value of maxlength with each change because if the maximum of characters changes that value may no longer be valid.

    Example working:

    $('input[name="tipouser"]').on("change", function(){
     
     //Como sugestão eu limpo o valor do input pois se o máximo 
     //de caracters muda aquele valor pode não ser mais válido:
     $("#InputUsuario").val("");
     
     
      if($(this).val() === '1'){
        $("#InputUsuario").attr({
          placeholder:"Insira seu CNPJ",
          maxlength:14
        });
      }
      
      if($(this).val() === '2'){
        $("#InputUsuario").attr({
          placeholder:"Insira seu CRC",
          maxlength:8
        });
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-lg-7">
        <div class="form-group">
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="tipouser"  value="1" checked>
                <label class="form-check-label" for="inlineRadio1">CNPJ</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="tipouser" value="2">
                <label class="form-check-label" for="inlineRadio2">CRC</label>
            </div>
        </div>
        <div class="form-group">                                   
            <input type="text" required="required" class="form-control"  name="usuario" id="InputUsuario" pattern="[0-9]+$" maxlength="14"  placeholder="Usuário">                                    
            <small class="text-muted">Apenas números</small>
       </div>
        
    09.04.2018 / 23:11