Select html element selected value

How to Get the Value of Selected Option in a Select Box

In this tutorial, you will learn how to get the value of the selected option in the select box using jQuery. There are two methods of getting the value of the selected option. You can either select text or find the position of it in a drop-down list by using the option:selected attribute or the val() method in jQuery.

The val() method returns the value of selected attribute value.

let selectedValue = $("#selectVal option:selected").val();

The text() method returns a string of the selected option.

let selectedValue = $("selectVal option:selected").text();

Let’s show what will return these two methods with the following example:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> form> label>Select Names: label> select class="selectVal"> option value="1">Tom option> option value="2">John option> option value="3">James option> option value="4">Ann option> option value="5">Maria option> select> form> script> $(document).ready(function( ) < $("select.selectVal").change(function( ) < let selectedItem = $(this).children("option:selected").val(); alert("You have selected the name - " + selectedItem); >); >); script> body> html>

The val() method will select the value of the option for example «1», and if you want to get the string «Tom» you can use the text() method.

Читайте также:  Unable to allocate memory python

The text() and val() Methods

The text() method will set or return the text content of the selected elements.

It returns the text content of all matched elements. When it is used to set content, it overwrites the content of all matched elements.

The val() method is an inbuilt method in jQuery, which is used to get the values of form elements (e.g., input, select, textarea). It will return the value of the value attribute of the first matched element.

Using Vanilla JavaScript

To get the value of the selected option in a select box using JavaScript, you can use the value property of the select element. Here’s an example:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> select id="my-select"> option value="option1">Option 1 option> option value="option2">Option 2 option> option value="option3">Option 3 option> select> script> var selectBox = document.getElementById("my-select"); var selectedValue = selectBox.value; alert(selectedValue); // prints the value of the selected option to the console  script> body> html>

In this example, we have a select box with three options, each with a different value. We’ve used JavaScript to get a reference to the select box using its ID, my-select . We’ve then used the value property of the select box to get the value of the currently selected option. We’ve stored this value in a variable called selectedValue and logged it to the console.

Note that if you want to get the text of the selected option instead of its value, you can use the textContent property of the selected option element. Here’s an example:

var selectBox = document.getElementById("my-select"); var selectedOption = selectBox.options[selectBox.selectedIndex]; var selectedText = selectedOption.textContent; alert(selectedText); // alerts the text of the selected option to the console

In this example, we’ve used the selectedIndex property of the select box to get the index of the currently selected option. We’ve then used this index to get a reference to the selected option element using the options property of the select box. We’ve used the textContent property of the selected option to get its text content and stored it in a variable called selectedText .

And here’s the full example:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> select id="my-select"> option value="option1">Option 1 option> option value="option2">Option 2 option> option value="option3">Option 3 option> select> script> var selectBox = document.getElementById("my-select"); var selectedOption = selectBox.options[selectBox.selectedIndex]; var selectedText = selectedOption.textContent; alert(selectedText); // alerts the text of the selected option to the console  script> body> html>

Источник

HTMLSelectElement

This interface inherits the properties of HTMLElement , and of Element and Node . HTMLSelectElement.autofocus A boolean value reflecting the autofocus HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. HTMLSelectElement.disabled A boolean value reflecting the disabled HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks. HTMLSelectElement.form Read only An HTMLFormElement referencing the form that this element is associated with. If the element is not associated with of a element, then it returns null . HTMLSelectElement.labels Read only A NodeList of elements associated with the element. HTMLSelectElement.length An unsigned long The number of elements in this select element. HTMLSelectElement.multiple A boolean value reflecting the multiple HTML attribute, which indicates whether multiple items can be selected. HTMLSelectElement.name A string reflecting the name HTML attribute, containing the name of this control used by servers and DOM search functions. HTMLSelectElement.options Read only An HTMLOptionsCollection representing the set of ( HTMLOptionElement ) elements contained by this element. HTMLSelectElement.required A boolean value reflecting the required HTML attribute, which indicates whether the user is required to select a value before submitting the form. HTMLSelectElement.selectedIndex A long reflecting the index of the first selected element. The value -1 indicates no element is selected. HTMLSelectElement.selectedOptions Read only An HTMLCollection representing the set of elements that are selected. HTMLSelectElement.size A long reflecting the size HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true , in which case it is 4. HTMLSelectElement.type Read only A string representing the form control’s type. When multiple is true , it returns «select-multiple» ; otherwise, it returns «select-one» . HTMLSelectElement.validationMessage Read only A string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation ( willValidate is false), or it satisfies its constraints. HTMLSelectElement.validity Read only A ValidityState reflecting the validity state that this control is in. HTMLSelectElement.value A string reflecting the value of the form control. Returns the value property of the first selected option element if there is one, otherwise the empty string. HTMLSelectElement.willValidate Read only A boolean value that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.

Instance methods

This interface inherits the methods of HTMLElement , and of Element and Node . HTMLSelectElement.add() Adds an element to the collection of option elements for this select element. HTMLSelectElement.blur() Deprecated Removes input focus from this element. This method is now implemented on HTMLElement . HTMLSelectElement.checkValidity() Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element (and returns false ). HTMLSelectElement.focus() Deprecated Gives input focus to this element. This method is now implemented on HTMLElement . HTMLSelectElement.item() Gets an item from the options collection for this element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly. HTMLSelectElement.namedItem() Gets the item in the options collection with the specified name. The name string can match either the id or the name attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly. HTMLSelectElement.remove() Removes the element at the specified index from the options collection for this select element. HTMLSelectElement.reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false ; if there are no problems, it returns true . HTMLSelectElement.setCustomValidity() Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: change event Fires when the user selects an option. input event Fires when the value of an , , or element has been changed.

Example

Get information about the selected option

/* assuming we have the following HTML  */ const select = document.getElementById("s"); // return the index of the selected option console.log(select.selectedIndex); // 1 // return the value of the selected option console.log(select.options[select.selectedIndex].value); // Second 

A better way to track changes to the user’s selection is to watch for the change event to occur on the . This will tell you when the value changes, and you can then update anything you need to. See the example provided in the documentation for the change event for details.

Specifications

Browser compatibility

See also

Источник

Оцените статью