Dan Dan - 22 days ago 5
HTML Question

Add/Remove values to field from checkbox values in Javascript

I have two fields: one is a checkbox (built with Scala), one is an input/text field. I am trying to add and remove values from the checkbox to the input field. I am trying to take multiple values and string together with a comma.

Here are my HTML fields:

<div class="column column1">
@for(service <- servicesList) {
<label><input type="checkbox" name="selectServices" value=@service.name><span>@service.name</span></label>
}
</div>

<input name="services" id="services">


I am using jQuery in a tag to try to record the onchange event:

$(document).ready(function(){

var $services = $('#services');
var $selectServices = $('#selectServices');

$selectServices.change(function(){
for (var i = 0, n = this.length; i < n; i++) {
if (this[i].checked) {
$services.val($services.val() + this[i].value);
}
else {
$services.val($services.val().replace(this[i].value, ""));
}
}

});
});


However, it seems that this will not "fire" when checking and unchecking the checkbox. I do not receive any errors or messages, so I am guessing it is not working or the code is incorrect.

I appreciate the help!

Answer

Try this example, you don't have to search and replace all the time, just set a new value:

$(function() {
  $('input[name=selectServices]').on('change', function() {
    $('#services').val($('input[name=selectServices]:checked').map(function() {
      return this.value;
    }).get());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
  <label>
    <input type="checkbox" name="selectServices" value='1'><span>1</span>
  </label>
  <label>
    <input type="checkbox" name="selectServices" value='2'><span>2</span>
  </label>
  <label>
    <input type="checkbox" name="selectServices" value='3'><span>3</span>
  </label>
  <label>
    <input type="checkbox" name="selectServices" value='4'><span>4</span>
  </label>
</div>
<input name="services" id="services">