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
What is SEO Analysis? SEO analysis is a detailed examination of a website’s performance in search engines. This analysis provides insights into the site’s current status and highlights areas needing improvement. SEO analysis is essential for defining a roadmap and building a successful strategy. Accurate analysis clarifies which keywords to focus on, how to resolve […]
Read More
Mid Level SEOWhat is Search Intent? Search intent refers to the underlying goal a user has when performing a search query. Google and other search engines do not just focus on keywords but also analyze their context to understand what users are really looking for. Search intent is generally categorized into four main types: informational, navigational, commercial […]
Read More
SEOWhat is Semantic SEO? Semantic SEO is an optimization approach that helps search engines better understand user intent. This method analyzes the relationships between words, context, and the purpose behind user queries, ensuring more accurate content matching. Based on our extensive experience in digital marketing, we can confidently say that content created with a semantic […]
Read More
SEOWhat is Site Speed? Site speed refers to how quickly a web page loads. (Site speed has multiple factors. The most important of these are initial load time and load speed.) This speed directly affects the visitor experience. A slow-loading site can cause users to leave the site and choose other pages. Additionally, search engines […]
Read More
Mid Level SEO