Fill in the input text value via checkbox

Asked

Viewed 4,280 times

2

I would like as the user was clicking on the options of checkbox, its value was added in an input text:

<div class="form-group col-md-7">
        <label class="checkbox-inline"><input type="checkbox" value="Laranja">Laranja</label>
        <label class="checkbox-inline"><input type="checkbox" value="Uva">Uva</label>
        <label class="checkbox-inline"><input type="checkbox" value="Banana">Banana</label>
    </div>      

When clicking on the 3, the input text was filled with the options.

It is possible?

3 answers

4


A simple way to do this is with javascript.

I added an input with the id="resultado" to use in javascript and created the Function add that receives value as a parameter.

Obs: It’s simple but it’s working.

function add(value){
  var resultado = document.getElementById('resultado');
resultado.value += " " + value;
}
<div class="form-group col-md-7">
        <label class="checkbox-inline"><input onclick="add(value)" type="checkbox" value="Laranja">Laranja</label>
        <label class="checkbox-inline"><input onclick="add(value)" type="checkbox" value="Uva">Uva</label>
        <label class="checkbox-inline"><input onclick="add(value)" type="checkbox" value="Banana">Banana</label>
    </div>
    <input type="text" id="resultado">

4

Using the same logic as the @Carlinhos reply, but adding the option to remove:

function add(_this){
  var resultado = document.getElementById('resultado');
  var value = _this.value;
  var hasAdd = resultado.value.search(_this.value) > 0
  if(_this.checked && !hasAdd){
    resultado.value += ' '+_this.value;
  }else if(!_this.checked && hasAdd){
    var er = new RegExp(_this.value, 'ig');
    resultado.value = resultado.value.replace(er, '');
  }
  resultado.value = resultado.value.replace(/ {2,}/g, ' ');
}
<div class="form-group col-md-7">
  <label class="checkbox-inline"><input onclick="add(this)" type="checkbox" value="Laranja">Laranja</label>
  <label class="checkbox-inline"><input onclick="add(this)" type="checkbox" value="Uva">Uva</label>
  <label class="checkbox-inline"><input onclick="add(this)" type="checkbox" value="Banana">Banana</label>
</div>
<input type="text" id="resultado">

0

I believe that code can help you!

</head>

<script type="text/javascript">
    function mudaNomeFruta(idInput){
        var fruta = document.getElementById(idInput).value;
        document.getElementById('textFruta').value = fruta;
    }

</script>

Orange Grape Banana

<input type="text" id="textFruta"></input>     

Browser other questions tagged

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