jeudi 17 novembre 2016

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!




Aucun commentaire:

Enregistrer un commentaire