Shape somewhat similar to aa_sp but more simplified:
$("#anonimo").on("change", function(){
$("form :text").val( this.checked ? "anônimo" : "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Deseja anonimato?
<input type="checkbox" id="anonimo">
<input type="text" id="nome" placeholder="seu nome">
<input type="text" id="email" placeholder="seu email">
<input type="text" id="telefone" placeholder="seu telefone">
</form>
The selector :type
go get everything type="text"
. But you can use your own types for each type of input to make it easier to enter mobile devices. In the case of email, type="email"
; telephone, type="tel"
...
In this case, you can use the selector input
since jQuery does not recognize selectors :email
or :tel
:
$("#anonimo").on("change", function(){
$("form input").not(this).val( this.checked ? "anônimo" : "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Deseja anonimato?
<input type="checkbox" id="anonimo">
<input type="text" id="nome" placeholder="seu nome">
<input type="email" id="email" placeholder="seu email">
<input type="tel" id="telefone" placeholder="seu telefone">
</form>
The .not(this)
is to skip the checkbox.
Another way is to add a common prefix to field id’s, so a more generic selector can be used:
$("#anonimo").on("change", function(){
$("[id^=user_]").val( this.checked ? "anônimo" : "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Deseja anonimato?
<input type="checkbox" id="anonimo">
<div>
<input type="text" id="user_nome" placeholder="seu nome">
</div>
<input type="email" id="user_email" placeholder="seu email">
<input type="tel" id="user_telefone" placeholder="seu telefone">
</form>
The selector [id^=user_]
will select all fields with id’s starting with user_
.
With pure Javascript
The selector is the same, only the construction changes:
document.querySelector("#anonimo").onchange = function(){
var campos = document.querySelectorAll("[id^=user_]");
for(var x=0; x < campos.length; x++){
campos[x].value = this.checked ? "anônimo" : "";
}
}
<form>
Deseja anonimato?
<input type="checkbox" id="anonimo">
<div>
<input type="text" id="user_nome" placeholder="seu nome">
</div>
<input type="email" id="user_email" placeholder="seu email">
<input type="tel" id="user_telefone" placeholder="seu telefone">
</form>
there are some ways to do this: via the fields, apply value directly by the ID, add a property to apply the value by this parameter,...
– aa_sp
By the ID would already be good size. Thanks for the feedback.
– João