Detect change in HTML select tag and get changed value in jQuery
In this tutorial, we are going to see how to check the changes and return the changed option value from an HTML select tag. We are going to use jQuery for this tutorial.
Here is an example of detecting the changes and then displaying the chosen option value from the select tag with the code snippets. Learning it from the code snippets is the easiest way to understand. Isn’t it?
Let’s create our select tag first. Below is the code of our HTML select tag which has some options from where you can choose a color:
<select id="color"> <option value="0" selected>Select color</option> <option value="red">Red</option> <option value="green">Green</option> <option value="blue" >Blue</option> <option value="yellow" >Yellow</option> </select>
Now we are going to detect the change and also detect and then display the chosen color from the color options of select tag.
You can see that we have set an id “color” for the select tag which will be used in our jQuery. Let’s see our jQuery code
The above jQuery code will first be checked any changes in the select tag. After that, it will check a condition. You can see in our HTML select tag that we have an option “select color” which has the value “0”. We don’t want to return the “0” value if it is selected. We only want to know if the chosen option is a color and then return the value.
Now run the code on your browser to test it. When you click and select an option except “Select color” from the select box, you will see the color value or color name through the alert box. The alert box used so that you can see if the code is working or not. The value you see is coming from the value attribute of the option that you select from the select tag.
The example you have seen in this tutorial is so useful and can be used in several places. I hope it will also be helpful to you. Thanks for showing interest in this tutorial post.