20.03.2023
In this article, we’d like to share how to add city and district options in contact form without using a extension or api.
You can use this code in both HTML & JS or plugins such as Contact Form 7. In this example, We’ve prepared this form via Contact Form 7. Syntax of form body is approrpriate to the plugin, however it’ll be also easier to adapt it to others.
At first step, we create options area in form body.
<label> First Name [text* first-name] </label>
<label> Last Name [text* last-name] </label>
<label> City [select* city id:form-field-City "Select" ] </label>
<label> District [select* district id:form-field-Ilceler "District" ] </label>
While creating a form via Contact Form 7, you can create form select area by typing it in square brackets, such as [select]. Additionally, you can specify an id by simply adding ‘id:’. Double quotes means placeholder text. It is easy enough to put a form element in label to type as <label>.
As you can see above, I specified city and district ids as form-field-City and form-field-District.
We will add Jquery library and neccessary JSON codes in our next step. You can add them both on top of Contact Form 7 body area or by adding them inside <script> tag. I’ve followed the second example and added these codes in <script> tag.
First, we call Jquery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
At second step, we add JSON which specifies the options for both city and district. This way, we may be able to make changes on code whenever it’ll be necessary to add or remove some options from our contact form.
<script> var data = [ { "il": "Ankara", "ilceleri": [ "Beypazarı", "Çamlıdere", "Çankaya", "Kalecik", "Kızılcahamam", "Nallıhan", "Polatlı" ] }, { "il": "İstanbul", "ilceleri": [ "Adalar", "Bakırköy", "Beşiktaş", "Beykoz", "Beyoğlu", "Eyüp", "Kadıköy", "Şişli" ] }, { "il": "İzmir", "ilceleri": [ "Bergama", "Bornova", "Çeşme", "Foça", "Karaburun", "Karşıyaka", "Seferihisar", "Selçuk" ] } ] </script>
Finally, we add JS code to run the function that will make our options and selections work.
<script> function search(nameKey, myArray){ for (var i=0; i < myArray.length; i++) { if (myArray[i].il == nameKey) { return myArray[i]; } } } $( document ).ready(function() { $.each(data, function( index, value ) { $('#form-field-Iller').append($('<option>', { value: value.il, text: value.il })); }); $("#form-field-Iller").change(function(){ var valueSelected = this.value; if($('#form-field-Iller').val() != null) { $('#form-field-Ilceler').html(''); $('#form-field-Ilceler').append($('<option>', { value: 0, text: 'Seçiniz' })); $('#form-field-Ilceler').prop("disabled", false); var resultObject = search($('#form-field-Iller').val(), data); $.each(resultObject.ilceleri, function( index, value ) { $('#form-field-Ilceler').append($('<option>', { value: value, text: value })); }); return false; } $('#form-field-Ilceler').prop("disabled", true); }); }); $("#form-field-Ilceler").change(function() { var IlceSelected = this.value; }); </script>
Oluşturduğumuz fonksiyonda önce tüm ‘il’ değerlerini bir array içinde oluşturduk. Daha sonra ikinci fonksiyonda #form-field-Iller’i çağırdık, buradaki value ve text’i parametreler üzerinden tanımladık. Üçüncü fonksiyonda change event’i kullanarak değişen seçeneğin value’sunu almasını söyledik. ‘$(‘#form-field-Ilceler’).append($(‘<option>’ { text: ‘Seçiniz’ } diyerek, formda henüz bir seçim yapılmamışken metin olarak ‘Seçiniz’ gözükeceğini, yapılan seçimden sonra o değer ile değişeceğini belirttik. Bir diğer önemli bir detay olarak, ‘ $(‘#form-field-Ilceler’).prop(“disabled”, true);’ koduyla, il alanında bir value yokken bu alan için disabled, true dedik, yani seçilemeyeceğini belirttik. Bir il seçilmesi, yani ilk alandan bir value gelmesi halinde buranın disabled, false olarak değişeceğini belirttik. Bu şekilde kullanıcılar forma girdiklerinde ilçe alanı kapalı olacak ve il alanında seçim yapmadan bir ilçe seçemeyecekler. Son fonksiyonda da, ‘il’ alanında yaptığımız gibi yine change event’i üzerinden ‘#form-field-Ilceler’ alanındaki değişen value’yu almasını söyledik.
Türkiye’deki tüm il ve ilçeleri kapsayan kodu Github repo’mda bulabilirsiniz.
Perfist Blog
Similar Articles
In this guide, we will explain what a session is in Google Analytics 4 (GA4), why session duration matters, which session metrics are available, and how to configure these settings. What is a Session in GA4? A session represents the group of interactions a user has with your website or mobile app within a given […]
Read More
Beginner Level Web/App AnalyticsWhat is GEO (Generative Engine Optimization)? GEO is a new generation optimization method that ensures content stands out in AI-supported search systems. It aims to produce content that can provide quick and clear answers to user questions. In addition to traditional SEO, a simple and understandable language that appeals to artificial intelligence is used. Why […]
Read More
Mid Level SEOGEO is an optimization method developed to ensure that content is better understood and recommended by AI-powered search engines. Previously, when writing content, the goal was solely to rank high on Google. Now, however, AI systems read these contents and present summaries to users. This is exactly where GEO steps in. It ensures that content […]
Read More
Mid Level Content MarketingUnderstanding how visitors reach your website is crucial for measuring the success of your marketing strategies. Google Analytics 4 (GA4) provides the Channel Grouping feature to analyze traffic sources. With channel grouping, you can categorize visitor traffic into specific segments and make more informed marketing decisions. What is Channel Grouping in GA4? GA4’s channel […]
Read More
Beginner Level Web/App Analytics