using .length but returning that 1 even it is empty javascipt
I had a multiple select box below.
<select multiple="multiple" id="states" name="states[]">
<option value="1">Alaska</option>
<option value="2">Florida</option>
</select>
Then in my JQuery
var states;
if($('#states').length < 1) {
console.log('no states', $('#states').length);
states = "undefined";
} else {
console.log('has states', $('#states').length);
states = $('#states').val();
}
In my comparison, if the array has no value or even has 2 or more, the array length still returns 1. My goal here is if it doesn't have a value selected, it would return undefined else the values in the multiple select.
I also trie开发者_开发问答d this one. If no values selected.
var states;
if(!$('#states').val()) {
console.log('no states', $('#states').length);
states = "undefined";
} else {
console.log('has states', $('#states').length);
states = $('#states').val();
}
Hope it helps:
const handleOnChange = (event) => {
var selectedStates;
const selectElement = $('#state-select');
const values = selectElement.val();
if(values.length < 1) {
console.log('no states', values.length);
selectedStates = undefined;
} else {
console.log('has states', values.length);
selectedStates = values;
}
console.log(selectedStates);
}
<select onchange="handleOnChange()" multiple="multiple" id="state-select" name="states[]">
<option value="1">Alaska</option>
<option value="2">Florida</option>
</select>
精彩评论