Form 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>Desejaanonimato?<inputtype="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 :type
selector will fetch everything that is type="text"
. But you can use own types for each type of input to facilitate entry into mobile devices. In the case of email, type="email"
; phone, type="tel"
...
In this case, you can use the input
selector since jQuery does not recognize the :email
or :tel
selectors:
$("#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>Desejaanonimato?<inputtype="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 ignore the checkbox.
Another way is to add a common prefix to the fields' 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>Desejaanonimato?<inputtype="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 [id^=user_]
selector will select all fields with id's beginning with user_
.
With pure JavaScript
The selector is the same, it just changes the construct:
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>