jQuery select option | how to get, add value in select option with jquery


jQuery select option | how to get, add value in select option with jquery

Working with select option in jQuery

In this tutorial, we will learn how to work with the select option in jQuery. This is quite useful in many scenarios, for example, you give options to your visitor to select a value from select/dropdown. User selects and presses a button and you can make a jQuery ajax call to bring some data in response.

An example of select / option

Similarly, you can use the option value retrieved by jQuery to change the presentation of the page as per user preference etc.

Below are a few examples to work with the select option in jQuery.

jQuery option select example

This example shows which option is selected in dropdown by the user. A dropdown has five values. As a user selects an option and presses the button, an alert will show the value with the jQuery select option.

Experience this example online



You can see, the text of selected option is shown by using ID of the dropdown. Now, what if you need to get the value of selected option rather text? See example below.

jQuery select option value example

The example below shows how to get the value of selected option. We will use same select / option dropdown, but the alert will show selected option’s value with jQuery.

Experience this example online



As you can see the alert will show two character code of color, placed in value.

jQuery add option to select example

In this example, we will show how simply you can add a value/text to the existing dropdown without reloading by using jQuery. We will use jQuery append method for that. In order to make it simple, we will add Green color to the existing dropdown; Text = Green and value = Gr.

As you press the button “Add new option” and then check select dropdown, you can see the new option is added.

Experience this example online



As you can see if you press “Show text” button after pressing “Add Option” and selecting Green, the alert will show Green.

Similarly, you can take user input from text boxes etc. and add options to the dropdown.

Related: jQuery append | jQuery ajax



Was this article helpful?