I'm trying to pass Select List Id as parameter in Function and check if it has value. If it doesn't have value, I want to get label text above this element and display error message, but I constantly get error: Uncaught Error: Syntax error, unrecognized expression: [object Object] option:selected, or if I remove option:selected I get undefined.
Can you please help me with this function?
Here is my code:
function ValidateDropDownListEmpty(dropDownListId) {
var elementId = $("#" dropDownListId);
var elementValue = $(elementId " option:selected").val();
var closestLabelText = $(elementId).parent().closest("label.dropdownLabel").text();
if (!elementValue) {
swal({
title: "Error!!!",
text: "Make Choice " closestLabelText "!!!",
showCancelButton: false,
showConfirmButton: true,
confirmButtonText: 'Ok',
dangerMode: true
}).then(function () {
$(elementId).focus();
});
return false;
};
return true;
};
CodePudding user response:
Better using vanilla JavaScript and reduce the jQuery usage.
document.querySelector('#my-select option:checked').value;
but if you want the jQuery way example to your code: it will be either this:
var elementValue = $(`#${dropDownListId} option:checked`).val();
or this:
var elementValue = $('#' dropDownListId ' option:checked').val();
CodePudding user response:
To get the value of the currently selected option in a select, try this:
const selectEl = document.getElementById('my-select');
const selectValue = selectEl.options[selectEl.selectedIndex].value;
console.log(selectValue);