Fill in the value of the input text via checkbox

1

I would like that as long as the user was clicking on the options of checkbox , the value of it 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>      

By clicking on the 3, the input text is filled in with the options.

Is it possible?

    
asked by anonymous 14.03.2016 / 14:57

3 answers

3

A simple way to do this is with javascript.

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

Obs : It was simple but it works.

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">
    
14.03.2016 / 18:23
3

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

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">
    
14.03.2016 / 19:01
0

I believe this 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>     

    
14.03.2016 / 18:33