Change placeholder by checking radio with jquery

Asked

Viewed 1,182 times

1

Hello, I’m trying to change the placeholder of an input by checking between 2 radio input values. Below is the js I tried to mount and 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>

  • Hello Rafael! Until today you have not marked an answer with . It is important for the community that the questions are finalized, and for this we need to mark an answer. If none of you answered it, you can ask questions to the AR (author of the answer), but do not leave questions open because it harms the purpose of the site. Obg!

4 answers

2


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

  1. On the line $('#tipousuario').prop('checked', actually need to apply the event to the element to capture when the value is changed, so we change to: $('.tipousuario').on('change',;
  2. On the line $('#tipousuario'), since there are 2 radio, doing the search for ID we can only take 1 element, because by definition each HTML document should not have elements with duplicated ID, so I renamed the ID’s to become unique and added the type class
  3. On the line $(this).attr({, we actually need to change the attributes in input text, then change to select by input ID: $('#InputUsuario')

Follow below with the adjustments:

$(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>
<div class="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>

  • I liked your answer +1

  • I really didn’t pay attention to these simple details. Thank you

1

Can do using ternary, clicking on radios buttons for name="tipouser".

Beyond the error in idduplicated s, there was another mistake: instead of maxlength you were using maxlenght (ending with ht).

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

  • Simply genius

  • Vlw , I did it fast and I didn’t realize the details.

1

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

I added the event change, to be able to take the change of states of the element radio.

I initialized the placeholder with Insira seu CNPJ.

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

Upshot:

html(I only removed the repeated ids)

<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: https://jsfiddle.net/bucnocqs/9/

0

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

Instead of taking your input for id I’ll pick him up by the attribute name.

Another important point is that in your example the value of this depends on how the function is called. It references the input amended, that is to say, <input type="radio" />.

So when you say:

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

you are modifying the attributes of input wrong.

Another important point is that the attribute name maxlength was wrong.

Suggestion: Clear the value of input every change because if the maximum character changes that value may no longer be valid.

Working example:

$('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>

<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"  name="usuario" id="InputUsuario" pattern="[0-9]+$" maxlength="14"  placeholder="Usuário">                                    
        <small class="text-muted">Apenas números</small>
   </div>

Browser other questions tagged

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