Bootstrap Contact Form: How to Add a New Dropdown (Select) Field

Updated on: Jul 22 2020 by Anli

Bootstrap Contact Form with Dropdown (Select) Field

After releasing many Bootstrap contact forms during the past few months, which you can find here, this is one of the recurring questions among the users of these forms:

How to add a new dropdown / select field to the contact form?

Some time ago I’ve written a tutorial about adding a new field to a Bootstrap contact form and particularly adding a dropdown field is not much different.

But, to some users this task might be confusing. That’s why today in this tutorial, I’ll explain step by step how to add a dropdown / select field to this Bootstrap contact form that I’ve chosen as an example (because I like that beautiful violet background).

At the end you can take the instructions below and apply them to my other templates, free and premium, to add new dropdown fields to the contact forms. They’re (almost) the same.

Let’s begin!

1. Introduction

As I mentioned above, for this tutorial I’ve used this form. The best way to benefit from this guide is to download that form and make the modifications yourself, step by step as you follow through the instructions. So, at the end you hopefully learn something new and are able to do it by yourself in the next project.

But, if you are in a hurry and just want a working contact form with a dropdown field, you can download the modified and ready-to-use version from the link at the end.

2. The HTML

Open the “index.html” file with your preferred editor and add the HTML code of the new select field. In this case, I’ve added a “Profession” field where the user has to make a choice from a list of professions, with this code:

<div class="form-group">
    <label for="c-form-profession">
        <span class="label-text">Profession:</span> 
        <span class="contact-error"></span>
    </label>
    <select name="profession" class="c-form-profession form-control" id="c-form-profession">
        <option value="Your profession...">Your profession...</option>
        <option value="Web design">Web design</option>
        <option value="SEO">SEO</option>
        <option value="Marketing">Marketing</option>
    </select>
</div>

Here is the resulting HTML code of the form:

<form role="form" action="assets/contact.php" method="post">
    <div class="form-group">
        <label for="c-form-name">
            <span class="label-text">Name:</span> 
            <span class="contact-error"></span>
        </label>
        <input type="text" name="name" placeholder="Your name..." class="c-form-name form-control" id="c-form-name">
    </div>
    <div class="form-group">
        <label for="c-form-email">
            <span class="label-text">Email:</span> 
            <span class="contact-error"></span>
        </label>
        <input type="text" name="email" placeholder="Your email address..." class="c-form-email form-control" id="c-form-email">
    </div>
    <div class="form-group">
        <label for="c-form-profession">
            <span class="label-text">Profession:</span> 
            <span class="contact-error"></span>
        </label>
        <select name="profession" class="c-form-profession form-control" id="c-form-profession">
            <option value="Your profession...">Your profession...</option>
            <option value="Web design">Web design</option>
            <option value="SEO">SEO</option>
            <option value="Marketing">Marketing</option>
        </select>
    </div>
    <div class="form-group">
        <label for="c-form-subject">
            <span class="label-text">Subject:</span> 
            <span class="contact-error"></span>
        </label>
        <input type="text" name="subject" placeholder="Message subject..." class="c-form-subject form-control" id="c-form-subject">
    </div>
    <div class="form-group">
        <label for="c-form-message">
            <span class="label-text">Message:</span> 
            <span class="contact-error"></span>
        </label>
        <textarea name="message" placeholder="Message text..." class="c-form-message form-control" id="c-form-message"></textarea>
    </div>
    <button type="submit" class="btn">Send message</button>
</form>

One thing to note here is that, unlike the form of the other tutorial, this form has visible labels. Inside the “label” tag there are two “span” tags: one for the label text and one for the error message to show if the user has left some field empty, hasn’t chosen an option from the dropdown field, or has entered an invalid email.

3. The CSS

You can find the CSS code of this form template in the “style.css” file. In this case we have to style the new field and make it match the design of the other fields, with this code:

.c-form-box select.form-control {
    height: 50px;
    margin: 0;
    padding: 0 20px;
    vertical-align: middle;
    background: #fff;
    border: 3px solid #fff;
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    font-weight: 300;
    line-height: 50px;
    color: #888;
    font-style: italic;
    -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;
    -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
    -o-transition: all .3s; -moz-transition: all .3s; -webkit-transition: all .3s; -ms-transition: all .3s; transition: all .3s;
}

.c-form-box select.form-control:focus {
    outline: 0; background: #fff; border: 3px solid #e8643e;
    -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
}

4. The PHP

We use some PHP code to validate the form’s fields from the server and send the email. The PHP code is in the “contact.php” file.

Here is the modified “contact.php” with the new field:

<?php

// Email address verification
function isEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

if($_POST) {

    // Enter the email where you want to receive the message
    $emailTo = 'contact.azmind@gmail.com';

    $name = addslashes(trim($_POST['name']));
    $clientEmail = addslashes(trim($_POST['email']));
    $profession = addslashes(trim($_POST['profession']));
    $subject = addslashes(trim($_POST['subject']));
    $message = addslashes(trim($_POST['message']));

    $array = array('nameMessage' => '', 
                   'emailMessage' => '', 
                   'professionMessage' => '', 
                   'subjectMessage' => '', 
                   'messageMessage' => ''
                  );

    if($name == '') {
    	$array['nameMessage'] = 'Empty name!';
    }
    if(!isEmail($clientEmail)) {
        $array['emailMessage'] = 'Invalid email!';
    }
    if($profession == 'Your profession...') {
    	$array['professionMessage'] = 'Choose a profession!';
    }
    if($subject == '') {
        $array['subjectMessage'] = 'Empty subject!';
    }
    if($message == '') {
        $array['messageMessage'] = 'Empty message!';
    }
    
    if($name!='' && isEmail($clientEmail) && $profession!='Your profession...' && $subject!='' && $message!='') {
        // Send email
        $message = "Message from: " . $name . "\r\n" . "Profession: " . $profession . "\r\n" . $message;
        $headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
        mail($emailTo, $subject . " (contact form template dropdown)", $message, $headers);
    }

    echo json_encode($array);

}

?>

In this new version of “contact.php” you can see that:

1) We’ve created a new variable to store the value of the new field:

$profession = addslashes(trim($_POST['profession']));

2) We’ve modified the response array and added “professionMessage” to store the result of the field validation:

$array = array('nameMessage' => '', 
               'emailMessage' => '', 
               'professionMessage' => '', 
               'subjectMessage' => '', 
               'messageMessage' => ''
              );

3) We’ve added the new field’s validation code:

if($profession == 'Your profession...') {
    $array['professionMessage'] = 'Choose a profession!';
}

4) We’ve added the new field’s value in the message (in the email’s text), if the validation is successful (if the user chooses a valid profession from the select field):

if($name!='' && isEmail($clientEmail) && $profession!='Your profession...' && $subject!='' && $message!='') {
    // Send email
    $message = "Message from: " . $name . "\r\n" . "Profession: " . $profession . "\r\n" . $message;
    $headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
    mail($emailTo, $subject . " (contact form template dropdown)", $message, $headers);
}

5. The Javascript (jQuery)

We use Javascript (jQuery) to make an AJAX call in the “scripts.js” file.

This means that when the user clicks the “Send message” button, we make a request to the “contact.php” file on the server passing all the fields’ values of the contact form (in the background, without reloading the page).

If the form validation is successful (see point 4 above), we hide the form and display a “Thank you” message. If not, we display the error messages for each field next to their labels (we add the error texts of each field in their respective “span” tags that have a “contact-error” class).

Here is the code in “scripts.js”:

/*
    Contact form
*/
$('.c-form-box form').submit(function(e) {
    e.preventDefault();
    var this_form_parent = $(this).parents('.c-form-box');
    var postdata = $(this).serialize();
    $.ajax({
        type: 'POST',
        url: 'assets/contact.php',
        data: postdata,
        dataType: 'json',
        success: function(json) {

            $('.c-form-box form label[for="c-form-name"] .contact-error').fadeOut('fast', function(){
                if(json.nameMessage != '') {
                    $(this).html('(' + json.nameMessage + ')').fadeIn('fast');
                }
            });
            $('.c-form-box form label[for="c-form-email"] .contact-error').fadeOut('fast', function(){
                if(json.emailMessage != '') {
                    $(this).html('(' + json.emailMessage + ')').fadeIn('fast');
                }
            });
            $('.c-form-box form label[for="c-form-profession"] .contact-error').fadeOut('fast', function(){
                if(json.professionMessage != '') {
                    $(this).html('(' + json.professionMessage + ')').fadeIn('fast');
                }
            });
            $('.c-form-box form label[for="c-form-subject"] .contact-error').fadeOut('fast', function(){
                if(json.subjectMessage != '') {
                    $(this).html('(' + json.subjectMessage + ')').fadeIn('fast');
                }
            });
            $('.c-form-box form label[for="c-form-message"] .contact-error').fadeOut('fast', function(){
                if(json.messageMessage != '') {
                    $(this).html('(' + json.messageMessage + ')').fadeIn('fast');
                }
            });
            if(json.nameMessage == '' && json.emailMessage == '' && json.professionMessage == '' && json.subjectMessage == '' && json.messageMessage == '') {
                this_form_parent.find('.c-form-top').fadeOut('fast');
                this_form_parent.find('.c-form-bottom').fadeOut('fast', function() {
                    this_form_parent.append("<p>Thanks for contacting us! We will get back to you very soon.</p>");
                    // reload background
                    $('.c-form-container').backstretch("resize");
                });
            }

        }
    });
});

As you can see, in this modified version we’ve just added the controls for the new “Profession” field.

6. Conclusions

That’s it! We have finally added our new dropdown / select field to the Bootstrap contact form. If you want, you can add other fields following the steps used here.

For any question or suggestions for improving the code, let me know in the comments.

Below you can find the live preview and download links.

Demo and Download

VIEW DEMO

DOWNLOAD: Bootstrap Contact Form with Dropdown Field (3976 downloads )

Want More?

Take a look at the Marco template. It comes with 15+ layouts and 30+ forms (contact, registration, login and subscription forms):

Marco Template: Contact Forms

Marco Template: Registration Forms

Filed under: Tutorials

3 Comments So Far

  1. Rodrigo says:

    I have exactly the same code, I can get the emails, but it doesn’t appears confirmation message when you submit the form. Can you help me out?

  2. peyman says:

    Hello, Everything works good but when users sends email they get this msg:{“nameMessage”:””,”emailMessage”:””,”professionMessage”:””,”subjectMessage”:””,”messageMessage”:””}

    how i can fix it?

  3. Sakhile says:

    I am having the same issue as Peyman, I’m getting the same{“nameMessage”:””,”emailMessage”:””,”professionMessage”:””,”subjectMessage”:””…. error.

Leave a Reply

To learn how we use your data when you comment, read our Privacy Policy here.