Accessing the values of multi-selector form elements using JQuery turns out to be a bit trickier than in how you construct the JQuery selector for the val( ) function. The val( ) function is designed to only return the first selected value in the matching form elements.
This page demonstrates a basic way to construct and program checkbox groups and select box options, accessing the data in an array and then presenting each selected value individually in a page element.
Hold down shift key to multiselect
These programs run as change event handlers on the checkbox or select multiple groups. The change event is registered to each group in different ways. In the case of the checkbox group by selecting by name using bracket notation. The multiple select element has the selector wrapper around the options so we can register the change event on that element using its ID attribute.
Since the val( ) function cannot return an array of selected values, we will use another JQuery function to do so, the map( ). map( ) takes an array as it's argument (the elements returned via the selector) and returns an array, transforming each index using the function that is passed as its argument. In this case the transformation takes the element and returns its value. This gives us an array of all the select values that we can assign to a variable.
We then invoke the JQuery each( ) function using the array as the selector (JQuery selectors can be DOM elements or Javascript objects). each( ) also takes a function, iterating and returning a value for each of the array elements. In our program we use the function to append each value as a paragraph to an output element on the page.
$("input[name=options]").change(function() {
var inputvalues = $('input:checked.option').map(function () {
return this.value;
});
$("#inputeach").html("");
$(inputvalues).each(function(index,value) {
$("#inputeach").append("<p>"+value+"</p>");
});
});
$("select#mark").change(function() {
var selectvalues = $('select#mark option:selected').map(function () {
return this.value;
});
$("#selecteach").html("");
$(selectvalues).each(function(index,value) {
$("#selecteach").append("<p>"+value+"</p>");
});
});