Programming Wordpress | 211 Views

Automatically Populate Form Fields with JavaScript

's Gravatar
Oct 30, 2021

This is the working Form whenever the state is choosed the city is shown in the next field

<form id="formID" action="#" method="post" name="contact-form">&nbsp;
<div class="mb-4"><select id="selstate" class="form-select validate[required]" name="state" data-errormessage-value-missing="* State required!">
<option disabled="disabled" selected="selected" value="">*Select a State</option>
<option value="Gujarat">Gujarat</option>
<option value="Madhya Pradesh">Madhya Pradesh</option>
<option value="Punjab">Punjab</option>
<option value="Telangana">Telangana</option>
</select></div>
&nbsp;
<div class="mb-4"><select id="selcity" class="form-select validate[required]" name="city" data-errormessage-value-missing="* City required!">
<option selected="selected" value="">*Select a City</option>
</select></div>
&nbsp;
<div class="mb-4"><button type="submit" id="btnSubmit" class="btn btn-primary btn-custom">Submit</button></div>
&nbsp;

</form>

For the Javascript Copy and Paste the Exact Code

<script>
(function($) {
//code for auto populate js for form state and city- aakash

// Map your choices to your option value
var lookup = {
'Gujarat': ['Ahmedabad', 'Surat', 'Vadodara'],
'Madhya Pradesh': ['Indore', 'Ujjain'],
'Punjab': ['Chandigarh', 'Rajpura','Ludhiana','Jalandhar'],
'Telangana' : ['Hyderabad'],
};

// When an option is changed, search the above for matching choices
$('#selstate').on('change', function() {
// Set selected option as variable
var selectValue = $(this).val();

// Empty the target field
$('#selcity').empty();
$('#selcity').append("<option value=''>Select Cities</option>");

// For each chocie in the selected option
for (i = 0; i < lookup[selectValue].length; i++) {
// Output choice in the target field
$('#selcity').append("<option value='" + lookup[selectValue][i] + "'>" + lookup[selectValue][i] + "</option>");
}
});

})(jQuery);
</script>

This code is a form that allows a user to select a state and city from dropdown menus and submit the form by clicking on the “Submit” button. Upon submission of the form, it sends the data to the server for processing.

The JavaScript code below the form is responsible for automatically populating the city dropdown menu based on the state selected by the user. It does this by creating an object named “lookup” that maps each state to its corresponding cities.

When a user selects a state, the JavaScript code listens to the change event of the state dropdown menu and empties the city dropdown menu. It then loops through the cities that correspond to the selected state and appends each city to the city dropdown menu.

This provides a better user experience as the user does not have to manually select the city dropdown based on the selected state.