How to get the name of a select option using jQuery

By FoxLearn 2/16/2024 9:28:10 AM   234
This post shows you how to get data attribute of selected option in javascript.

For example

<select id="ddlCategory">
    <option vlaue="1"></option>
    <option value="2" name="cat">Category 1</option>
    <option value="4" name="cat">Category 2</option>
    <option value="5" name="cat">Category 3</option>
    <option value="6" name>Category 4</option>
    <option value="7" name>Category 5</option>
</select>

To get name of a select option in javascript attribute you can write

var cat = $("#ddlCategory option:selected").attr("name");

jquery get data attribute value of selected option

As you know, name isn't a valid attribute of an option element, you can use a data parameter, like this:

<option value="foo" data-name="foo">Foo</option>

then modify your javascript get data attribute of selected option

$('option:selected', this).data("name")).css("display", "block");

if you want to display block or none.