user3782230
user3782230

Reputation: 155

jQuery Select List Id as Parameter in Function and Get Selected Value

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;
};

Upvotes: 0

Views: 533

Answers (2)

Gal Gur-Arie
Gal Gur-Arie

Reputation: 394

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();

Upvotes: 1

Boguz
Boguz

Reputation: 1823

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);

Upvotes: 1

Related Questions