Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit d882fde

Browse files
committed
feat(jqLite): return [] for .val() on <select multiple> with no selection
Fixes #14370 BREAKING CHANGE: For the jqLite element representing a select element in the multiple variant with no options chosen the .val() getter used to return null and now returns an empty array. To migrate the code follow the example below: Before: HTML: <select multiple> <option>value 1</option> <option>value 2</option> </select> JavaScript: var value = $element.val(); if (value) { /* do something */ } After: HTML: <select multiple> <option>value 1</option> <option>value 2</option> </select> JavaScript: var value = $element.val(); if (value.length > 0) { /* do something */ }
1 parent 121f649 commit d882fde

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/jqLite.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,7 @@ forEach({
699699
result.push(option.value || option.text);
700700
}
701701
});
702-
return result.length === 0 ? null : result;
702+
return result;
703703
}
704704
return element.value;
705705
}

test/jqLiteSpec.js

+25
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,31 @@ describe('jqLite', function() {
10341034
'<option>test 2</option>' +
10351035
'</select>').val()).toEqualOneOf(null, []);
10361036
});
1037+
1038+
it('should get an empty array from a multi select if no elements are chosen', function() {
1039+
// In jQuery < 3.0 .val() on select[multiple] with no selected options returns an
1040+
// null instead of an empty array.
1041+
// See https://github.com/jquery/jquery/issues/2562 for more details.
1042+
if (isJQuery2x()) return;
1043+
1044+
expect(jqLite(
1045+
'<select multiple>' +
1046+
'<optgroup>' +
1047+
'<option>test 1</option>' +
1048+
'<option>test 2</option>' +
1049+
'</optgroup>' +
1050+
'<option>test 3</option>' +
1051+
'</select>').val()).toEqual([]);
1052+
1053+
expect(jqLite(
1054+
'<select multiple>' +
1055+
'<optgroup disabled>' +
1056+
'<option>test 1</option>' +
1057+
'<option>test 2</option>' +
1058+
'</optgroup>' +
1059+
'<option disabled>test 3</option>' +
1060+
'</select>').val()).toEqual([]);
1061+
});
10371062
});
10381063

10391064

0 commit comments

Comments
 (0)