Hudson Medeiros
Hudson Medeiros

Reputation: 321

Fill input according selected checkboxes (jQuery)

I have some checkboxes in my web page:

<input type="checkbox" id="alphabet" name="alphabet" value="A"> A <br />
<input type="checkbox" id="alphabet"name="alphabet" value="B"> B <br />
<input type="checkbox" id="alphabet"name="alphabet" value="C"> C <br />

<br />

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

Is there any way to fill a input camp "toggling" these checkboxes?

The final result maybe something like:

A, B, C...

Upvotes: 0

Views: 1058

Answers (1)

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

Try this code by listening to change event and then setting the value.

(function() {
  $('input:checkbox').change((e) => {
    if ($(e.currentTarget).is(':checked')) {
      var curVal = $('#selected').val();
      if (curVal) {
        $('#selected').val(curVal + ', ' + e.currentTarget.value);
      } else {

        $('#selected').val(e.currentTarget.value);
      }
    } else {
      var curVal = $('#selected').val().split(',');
      var filteredVal = curVal.filter(el => el.trim() !== e.currentTarget.value)
      $('#selected').val(filteredVal.join(','));
    }
  });
})();
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<input type="checkbox" id="alphabet" name="alphabet" value="A"> A <br />
<input type="checkbox" id="alphabet" name="alphabet" value="B"> B <br />
<input type="checkbox" id="alphabet" name="alphabet" value="C"> C <br />

<br />

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

Upvotes: 2

Related Questions