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 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 SEOWhat is Structured Data? Structured data is a coding system used to help search engines better understand the content of a website. Implemented using formats like JSON-LD and Microdata, it enables the presentation of detailed information such as products, events, and business details in a comprehensible way. This is especially advantageous for e-commerce websites, as […]
Read More
Mid Level SEOIn the digital marketing world, user-generated content (UGC) is becoming increasingly important. UGC includes videos where users share their own experiences, opinions, and creativity in promoting brands and products. So, why are UGC videos so significant in digital marketing strategies? 1. Trustworthiness and Authenticity User-generated content creates a more trustworthy perception for consumers compared to […]
Read More
Performance MarketingWith the transition from Universal Analytics to Google Analytics 4, there may be some issues you need to resolve. One of these issues is “unassigned” traffic. Dimensions appearing as “unassigned” / (not set) in reports negatively impact your ability to analyze and optimize. We will discuss the causes of “unassigned” traffic in your GA4 reports […]
Read More
Beginner Level Web/App Analytics