How to change the value of a text field according to the item selected in a select field using jQuery
One of our Drupal projects required the value of a text field to be changed according to the country selected in a particular select field. This is a common situation encountered by web developers when working on HTML. This can be easily achieved using jQuery. Read on to know more
Suppose you have a text field with id text-country and a select field with id select-country. If you want to change the value of the text field with the value selected in the select field, add the following code in your JS file.
jQuery("#select-country").change(function(){
var country = jQuery("#select-country").find(":selected").text();
jQuery("#text-country").val(country);
});
The above code does the following.
When an item is selected from the select box, it will take the value selected and store it in a variable 'country'. Then, assign the value of country variable to the text field.
Thus, by adding the above code in our JS file, we can change the value of a text field according to the item selected in a select field.