1

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" [email protected]><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!

4 Answers 4

1

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">

does the $(function() {} go into the $(document).ready(function(){}?

No, it is short-hand or equivalent for the same.

Sign up to request clarification or add additional context in comments.

2 Comments

does the $(function() {} go into the $(document).ready(function(){}?
This worked --- thanks @Arvind -- <script type="text/javascript"> $(document).ready(function(){ $('input[name=selectServices]').on('change', function() { $('#services').val($('input[name=selectServices]:checked').map(function() { return this.value; }).get()); }); }); </script>
1

This is just an addition on @Halcyon his answer so you can create a nicer list, in stead of the replace method. @Halcyon is most definitely the correct answer why your check boxes aren't working. This is just a better solution handling values.

$(document).ready(function(){
  var $services = $('#services');
  var $selectServices = $('.selectServices');
  $selectServices.change(function(){
    updateServices();
  }); 
  function updateServices() {         
     var allVals = [];
     $('.selectServices:checked').each(function() {
       allVals.push($(this).val());
     });
     $services.val(allVals);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="column column1">
    
        <label><input class="selectServices" type="checkbox" name="selectServices[]" value="Foo"><span>Foo</span></label>
        <label><input class="selectServices" type="checkbox" name="selectServices[]" value="Bar"><span>Bar</span></label>
        <label><input class="selectServices" type="checkbox" name="selectServices[]" value="FooBar"><span>FooBar</span></label>

</div>

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

Comments

1

$('#selectServices') selects by id, there are no elements with that id. Ids must be unique so you can't use them in this case. I also wouldn't recommend using name because input elements should have unique names. You can use class:

<label><input type="checkbox" class="selectServices" ...

Then use .selectServices in jQuery. And:

var $selectServices = $('.selectServices');
$selectServices.change(function(){
    if (this.checked) {
        $services.val($services.val() + this.value);
    } else {
        $services.val($services.val().replace(this.value, "")); 
    }
}); 

4 Comments

To add to this, the simple replace solution is not going to work nicely. If you have the values : Foo, Bar, FooBar for example. You can have really nasty outcomes like BarBarFooFoo by pressing some checkboxes randomly. i.imgur.com/AzBEp3Q.png
@Halcyon - I added the id to the selectServices checkbox, however, the function does not do anything - no error, nothing is changing. I have the code in a <script type="text/javascript"> tag, but it does nothing.
Don't use ids. Ids have to be unique. $('#selectServices') will give you at most 1 element, likely either the first one or the last one but it could be any really.
@Halcyon - That worked, however, if I wanted to not add a comma at the beginning of the string, how would I do that. I have this right now: $selectServices.change(function(){ if (this.checked) { if ($services.val() == "";) { $services.val(this.value); } else { $services.val($services.val() + "," + this.value); } } else { $services.val($services.val().replace(this.value, "")); } });
0

Your code will fire if you add ID's to your inputs:

<input type="checkbox" name="selectServices" id="selectServices" value="" />

and

<input name="services" id="services" type="text" />

4 Comments

This is really bad practice to have multiple DOM elements with the same ID. Element IDs should be unique within the entire document. @Halcyon solution of changing it to classes or any DOM selection method is better than this.
The two inputs do not have identical ID's... selectServices vs. services = UNIQUE.
selectServices are multiple checkboxes generated by a loop... I'm not even talking about services
@Timmetje sorry, my point wasn't to create, alter or remove loops, simply to add ID's to the elements if the OP is going to reference the elements using ID, not trying to do the OP's work for them but simply answer the actual question of why the onchange event does not "fire" when checking and unchecking the checkboxes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.