How to Disable Click Event in jQuery (Enable/Disable Button Click)

On 3/20/2017 Be the first to comment!

Hi! Let's see how to disable click event in jquery here. As a web developer you might have faced the problem of users submitting forms more than once especially ajax forms. Due to slow internet connection or hundred other reasons there is a lot of chance for users to click submit buttons again and again in a web form. To overcome this you can simply restrict users to click button more than once with the help of jquery. You can do this in two ways. One, you can disable the button which makes it to grey out and not respond to clicks. Or you can simply unbind click event from button. With this the button won't be disabled but just the click event alone. Here I'm going to show you how to disable click event for button.

jquery disable click event after click
Read Also:

How to Disable Click Event in jQuery?

Just like disabling click event you can enable it at any time with jquery. For that we need jquery's on() and off() methods and they are used to attach and remove event handlers from an element. The methods not only work for buttons but for other html elements too.

  • On() is used to attach event handlers to html elements
  • Off() is used to remove event handlers from html elements

First let's add a checkbox and button to html page. When the checkbox is ticked, button click event should be disabled and enabled when unchecked.

<input type="checkbox" id="chkbox" />Disable Click
<button id="submit">Click Me</button>

jQuery Script:

Let's write separate handler function for button click event so that you can use it in as many places as you want.

function clickButton() {
    alert('Button clicked!');
}

Next the event handler for button clicks.

$('#submit').on('click', clickButton);

Then disable the click event when checkbox is ticked.

$('document').ready(function() {
    $('#chkbox').on('change', function(){
        if($(this).prop('checked'))
            $('#submit').off('click');
        else
            $('#submit').on('click', clickButton);
    });
});

That will take care of enabling/disabling click event for button.

Complete Script:

<!DOCTYPE html>
<html>
    <head>
        <title>Enable and Disable Click Event in jQuery</title>
    </head>
    <body>
        <input type="checkbox" id="chkbox" />Disable Click
        <button id="submit">Click Me</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
        <script type="text/javascript">
        $('document').ready(function() {
            $('#chkbox').on('change', function(){
                if($(this).prop('checked'))
                    $('#submit').off('click');
                else
                    $('#submit').on('click', clickButton);
            });
            
            $('#submit').on('click', clickButton);
            
            function clickButton() {
                alert('Button clicked!');
            }
        });
        </script>
    </body>
</html>
Read Also:

That explains about how to enable and disable click event in jquery. I hope you find this jquery snippet useful. Meet you in another interesting tutorial.

Add Remove Textbox Dynamically using jQuery, PHP & Bootstrap

On 3/14/2017 Be the first to comment!

Hi! In today's post let's see how to add remove textbox dynamically using jquery, php and bootstrap css. Letting users to dynamically add/remove form fields on fly and submitting form will give users a certain level of control over their input. The process is pretty straight forward and with little jquery script you can implement this dynamic feature in any php form or html form. The idea here is to create a textbox attached with a '+' (Plus) button/sign at the end. When user clicks on '+' button additional textboxes will be added to the form and the dynamically added textboxes will come attached with '-' sign/button to them. If user wants to remove a textbox then they have to click on '-' button and the specific textbox will be deleted on fly.

I have used bootstrap for designing form elements here but it's optional. You are free to go without it and the jquery script will work for non-bootstrap form too (of course with some minor tweaks).

dynamically add remove textbox using jquery php bootstrap
Also Read:

How to Add/Remove Textbox Dynamically using jQuery & PHP?

First you need to add a single textbox and a plus button probably within a form. And make the textbox input as array so that users can duplicate it on fly.

HTML Markup:

<div class="textbox-wrapper">
    <div class="input-group">
        <input type="text" name="text_arr[]" class="form-control" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-success add-textbox"><i class="glyphicon glyphicon-plus"></i></button>
        </span>
    </div>
</div>

Next you need to add jquery function to create duplicate textbox dynamically when user clicks on the Plus button.

jQuery Script:

$(document).ready(function() {
    var max = 10;
    var cnt = 1;
    $(".add-textbox").on("click", function(e){
        e.preventDefault();
        if(cnt < max){
            cnt++;
            $(".textbox-wrapper").append('<div class="input-group"><input type="text" name="text_arr[]" class="form-control" /><span class="input-group-btn"><button type="button" class="btn btn-danger remove-textbox"><i class="glyphicon glyphicon-minus"></i></button></span></div>');
        }
    });
});

The above function will limit the maximum number of text fields users can add to the form at any time. When it reaches the maximum the script will restrict users from adding any more textboxes.

Next is the textbox removal part. The following function will remove textbox from the form when user clicks on the Minus button.

$(".textbox-wrapper").on("click",".remove-textbox", function(e){
    e.preventDefault();
    $(this).parents(".input-group").remove();
    cnt--;
});

Done! Now we have both html and jquery code in place. Run the script and you will get a form with single textbox and a '+' button attached to it.

add remove input fields dynamically jquery php

Clicking on the plus button will add more textboxes on fly.

add textbox dynamically jquery php

On the other hand click on a minus button and the textbox will get removed from the form.

remove input field dynamically jquery php

Complete Script:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Remove Textbox Dynamically using jQuery, PHP & Bootstrap</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style type="text/css">
    .input-group {
        margin-top: 10px;
        margin-bottom: 10px;
    }
    </style>
</head>
<body>
    <div class="container" style="margin-top: 30px;">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="panel panel-success">
            <div class="panel-body">
                <form name="demo-form" method="post">
                <div class="textbox-wrapper">
                    <div class="input-group">
                        <input type="text" name="text_arr[]" class="form-control" />
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-success add-textbox"><i class="glyphicon glyphicon-plus"></i></button>
                        </span>
                    </div>
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="Submit Form" class="btn btn-lg btn-block btn-success"/>
                </div>
                </form>
            </div>
        </div>
    </div>
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        var max = 10;
        var cnt = 1;
        $(".add-textbox").on("click", function(e){
            e.preventDefault();
            if(cnt < max){
                cnt++;
                $(".textbox-wrapper").append('<div class="input-group"><input type="text" name="text_arr[]" class="form-control" /><span class="input-group-btn"><button type="button" class="btn btn-danger remove-textbox"><i class="glyphicon glyphicon-minus"></i></button></span></div>');
            }
        });
       
        $(".textbox-wrapper").on("click",".remove-textbox", function(e){
            e.preventDefault();
            $(this).parents(".input-group").remove();
            cnt--;
        });
    });
    </script>
</body>
</html>

Handling POST Data in PHP:

Like I said before, the textbox field is an array. When user submits the form you can access the post data like this in php.

<?php
$myarray = $_POST['text_arr'];
foreach($myarray as $val){
    ...
    ...
}
?>
Also Read:

Likewise you can add or remove textbox dynamically using jquery and bootstrap. The same script will work for other input fields too. Just replace textbox with any other form inputs and the rest would be the same. I hope you like this script. Please don't forget to share it in your social circle.

Back To Top Button using HTML CSS and jQuery

On 3/08/2017 Be the first to comment!

Hi! Let's see how to implement back to top button using html, css and jquery. Good user experience means a lot for websites. If it fails, people will leave your site no matter how good and informative it is. Accessibility is the best way to ensure good user-experience. If people find a website easy to navigate through then they visit more pages and stay longer on the site.

Now a day's several websites uses infinite scroll technique and shows so much of content in a single page itself. Imagine how annoying it would be if user has to scroll back to the top of the page after going all the way down to read through long contents. In such case having a back-to-top button will help users to scroll back to the top of the page with just a single mouse click. And I'm going to show you how to add this back to top button with just css and jquery alone.

HTML Back To Top Button CSS jQuery
Also Read:

Implementing Back To Top Button using HTML, CSS & jQuery:

Even though we call it as a button, this Back to top button is a link that lets users to smoothly scroll back to the top of the page when clicked. It enhances user experience on long page websites. As for creating button, I'm going with pure css but you are free to use images in case you want a fancy one.

Come let's see how to implement back to top button on websites.

Step 1) Create Back To Top Button with HTML

First you need to create back to top button. This is the html markup for adding button to a web page.

<a href="#" class="back-to-top" title="Back To Top">&uarr;</a>

Step 2) Style Button with CSS

Next you need to add some styles to make sure the link look like an actual button. The following css will create a circle button with up arrow in it. And also position it at the bottom right corner of the page.

body {
    height: 5000px;
}

.back-to-top {
    position: fixed;
    bottom: 40px;
    right: 40px;
    color: #FFF;
    background: #41CAD4;
    line-height: 30px;
    text-align: center;
    text-decoration: none;
    width: 32px;
    height: 32px;
    border: 0;
    border-radius: 50%;
    display: none;
    cursor: pointer;
    z-index: 9999;
}

.back-to-top:hover {
    background: #2DB6C0;
}

Step 3) Scroll Back to Top with jQuery

Finally you need to add some jquery script for the button to work.

In the second step, we have positioned the button at the bottom-right corner of the page, but it will be kept hidden until user starts scrolling. The back-to-top button will only appear when the page is scrolled down a little. For that you need to add scroll event to the page and display the button when it cross over 100 pixels mark.

$(document).ready(function(){ 
    $(window).on('scroll', function() {
        if ($(this).scrollTop() > 100) {
            $('.back-to-top').fadeIn();
        } else {
            $('.back-to-top').fadeOut();
        }
    });
});

Then you have to ensure the page smoothly scrolls back to top of the window on button click. For that you have to use animate() function on button click event.

$('.back-to-top').on('click', function(e) {
    e.preventDefault();
    $('html,body').animate({scrollTop: 0}, 600);
});

Done! Now you have everything in place. Run the script and scroll down the page a little. Now a small round button will appear at the bottom right corner of the page and stay there as long as you go down. Click on the button at any time and it will take you back to the top of the page. Once you are at the top, the button will disappear.

Complete Script:

<!DOCTYPE html>
<html>
    <head>
        <title>Scroll Back To Top using HTML, CSS and jQuery</title>
        <style type="text/css">
        body {
            height: 5000px;
        }
        
        .back-to-top {
            position: fixed;
            bottom: 40px;
            right: 40px;
            color: #FFF;
            background: #41CAD4;
            line-height: 30px;
            text-align: center;
            text-decoration: none;
            width: 32px;
            height: 32px;
            border: 0;
            border-radius: 50%;
            display: none;
            cursor: pointer;
            z-index: 9999;
        }
        
        .back-to-top:hover {
            background: #2DB6C0;
        }
        </style>
    </head>
    <body>
        <!-- page content goes here -->
        <a href="#" class="back-to-top" title="Back To Top">&uarr;</a>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){ 
            $(window).on('scroll', function() {
                if ($(this).scrollTop() > 100) {
                    $('.back-to-top').fadeIn();
                } else {
                    $('.back-to-top').fadeOut();
                }
            });
            
            $('.back-to-top').on('click', function(e) {
                e.preventDefault();
                $('html,body').animate({scrollTop: 0}, 600);
            });
        });
        </script>
    </body>
</html>
Also Read:

Likewise you can create back to top button with html, css and jquery. As for this demo, I haven't added any content to the page, so I have set some height to the body section of the page. The step is not required while implementing it on actual website. I hope you find this script useful and don't forget to share it in social media.

Twitter Bootstrap Jumbotron Tutorial with Examples: Beginners Guide

On 3/03/2017 6 Comments so far

Jumbotron is one of the best features of Twitter Bootstrap Framework and we'll see in this tutorial how to build bootstrap jumbotron with background images. It is a light weight component that can be used to showcase the featured content of websites. You can also add a compelling call-to-action to the component. All sorts of websites especially commerce sites can get beneficial by using bootstrap jumbotron unit in their landing pages, and make the user to take desired action.

If you want to learn more about customizing bootstrap framework, read through our earlier tutorials on similar topic.

  1. Change Bootstrap Navbar Color, Text & Hover Color
  2. How to Customize Bootstrap Breadcrumb Styles
  3. How to Create Bootstrap Buttons with Icons

Now coming back to bootstrap jumbotron tutorial let us see some examples.

Bootstrap Jumbotron Examples

To build jumbotron unit to your landing pages, add a <div> block to the page and include the css class ".jumbotron" to it. This places an outer wrapper for the jumbotron unit. Next add necessary heading and text to it with <h1> and <p> element as usual. Finally add an anchor link with css classes ".btn", ".btn-success" and ".btn-lg" to make the link to look like a button. Use the href attribute of the link to redirect the user on click to the url of your choice.

<div class="container">
    <div class="jumbotron">
        <h1>Nature</h1>
        <p>Breathtaking Nature Stock Photos for FREE!</p>
        <p><a href="#" class="btn btn-success btn-lg">Click Here »</a></p>
    </div>
</div>

The above html markup will give you a simple text based jumbotron.

twitter-bootstrap-jumbotron-default-template-example

Add Background Image to Bootstrap Jumbotron

Do you want to add background image to this jumbotron component? Then you have to override the bootstrap's ".jumbotron" css class.

The easy way to do is to create a new style sheet and add this piece of code to it.

.jumbotron {
    /* add bootstrap jumbotron background image */
    background: url("images/banner.jpg");
    /* change bootstrap jumbotron text color */
    color: #FFF;
}

Two style renovations have been added above to the jumbotron class. One is to add a background image to its container and the second one to change the text color to white to make it stand out from the background image.

Just name your new style sheet as "custom.css" and link it after the "bootstrap.min.css" file in the landing page. And you are done!

Here is the new bootstrap jumbotron with a nice background image.

bootstrap-jumbotron-background-image

Make Jumbotron to Full Width of the View Port

Want the bootstrap jumbotron unit to span to the full width of the view port (screen) and without rounded corners? Just place the jumbotron outside all the container class and instead add ".container" class within jumbotron like this.

<div class="jumbotron">
    <div class="container">
        <h1>Nature</h1>
        <p>Breathtaking Nature Stock Photos for FREE!</p>
        <p><a href="#" class="btn btn-success btn-lg">Click Here »</a></p>
    </div>
</div>

Now we get the full width jumbotron without left and right padding.

bootstrap-jumbotron-full-width-remove-rounded-corner

Those are the simple bootstrap customizations you can do in seconds to build bootstrap jumbotron with background images.

Also Read:

And that was all about using twitter bootstrap jumbotron plug-in.

Simple Image and File Upload in CodeIgniter with Validations & Examples

On 3/03/2017 11 Comments so far

Codeigniter provides a wide number of helper class and libraries for rapid application development. Upload library is one among them that makes file uploading process in Codeigniter a breeze. We'll see how to do file and image upload in codeigniter in this tutorial.

File Upload in CodeIgniter

First of all, we need a destination folder to store all the uploaded files. So create a folder named 'uploads' in the root folder. Make sure it is writable for the uploading process to work.

Read Also:

Create Controller

Create a controller file 'uploadfile.php' inside 'application\controllers' folder in codeigniter.

<?php
class uploadfile extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    //index function
    function index()
    {
        //load file upload form
        $this->load->view('upload_file_view');
    }

    //file upload function
    function upload()
    {
        //set preferences
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'txt|pdf';
        $config['max_size']    = '100';

        //load upload class library
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('filename'))
        {
            // case - failure
            $upload_error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_file_view', $upload_error);
        }
        else
        {
            // case - success
            $upload_data = $this->upload->data();
            $data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
            $this->load->view('upload_file_view', $data);
        }
    }
}
?>

The upload() method in the codeigniter controller is where the actual file upload process takes place. Here we load the 'upload' library with the statement $this->load->library('upload', $config); . The $config is the array where we set preferences to control the uploading process. This is where we define the file uploading path, allowed file extensions, maximum file size etc.

This controller upload() method will be invoked on form submission, and the file will be validated and shows the validation error in case it fails. Else it will upload the file to the destination folder.

We have used some of the important methods of the 'upload' class library in our controller.

  • The callback, $this->upload->do_upload() will upload the file selected in the given field name to the destination folder. Note that the parameter to this method is optional and if it is not mentioned, then it expects the file from the input field with name 'userfile'. So if you set the file input with name other than 'userfile' make sure you pass the field name as parameter to the do_upload() function.
  • The callback $this->upload->display_errors() returns the error message if the do_upload() method returns false.
  • And the callback $this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.

Create View

Create the view file 'upload_file_view.php' inside 'application\views' folder. This view file contains a simple upload form with file input and a submit button.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter File Upload Form</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 well">
        <legend>CodeIgniter File Upload Demo</legend>
        <?php echo form_open_multipart('uploadfile/upload');?>

        <fieldset>
            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <label for="filename" class="control-label">Select File to Upload</label>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <input type="file" name="filename" size="20" />
                        <span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <input type="submit" value="Upload File" class="btn btn-primary"/>
                    </div>
                </div>
            </div>
        </fieldset>
        
        <?php echo form_close(); ?>
        <?php if (isset($success_msg)) { echo $success_msg; } ?>
        </div>
    </div>
</div>
</body>
</html>

The above view will produce an upload form like this.

codeigniter-file-upload-demo-form
CodeIgniter File Upload Demo Form

Generally I use bootstrap css framework to design the html forms for all my tutorials. This tutorial is no exception and I have used bootstrap components to give a nice look and feel to our upload form. Also I have set the form type to 'multipart' for the file uploading to work. (If you are a newbie to bootstrap then take a look at this tutorial on using bootstrap with codeigniter php framework to learn more).

When the user submits the form, it will be validated against the preferences set by the $config[] array. If the file is not selected or any other form validation error occurs, it is displayed below the file input like this.

file-upload-validation-error

If the validation succeeds and the file is uploaded successfully to the destination folder, a success message will be displayed at the bottom of the form like this.

file-upload-validation-success

Uploading Images in CodeIgniter

If you want to restrict the user to upload only image files in codeigniter, then you can set the preferences to something like this in the controller file,

<?php
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'png|jpg|gif';
    $config['max_size'] = '150';
    $config['max_width'] = '1024'; /* max width of the image file */
    $config['max_height'] = '768'; /* max height of the image file */
?>

Hence in this way you can restrict the users to upload only images. Moreover all those image files should fall under the maximum file size, width and height set by you :).

Read Also:

And that explains the file and image uploading process in codeigniter.

Last Modified: 3-Mar-2017

How to Send Email in CodeIgniter via SMTP Server

On 3/03/2017 8 Comments so far

Codeigniter comes with many built-in helpers and libraries for robust development. Of which its email library is a little gem that you can configure and send mails on fly. Here is a simple example to send email in codeigniter using smtp protocol. We'll see how to send mail with attachments through gmail, but you can use any third party smtp servers. Just get the smtp settings from the service provider and use it instead of gmail settings and you are done.

To send mail in codeigniter, you have to configure your email preferences like mail protocol, smtp authorization, html or plain text mail etc. These email preferences can be defined either globally or at the time of sending mails (like inside controllers).

Also Read:

Configure Email Preferences

Here we'll configure our email preferences globally in codeigniter. Create a file named 'email.php' inside 'application/config' folder and add the below settings to it. These settings will be loaded and used automatically for sending emails.

<?php
    $config['protocol'] = 'smtp';
    $config['smtp_host'] = 'ssl://smtp.gmail.com'; //change this
    $config['smtp_port'] = '465';
    $config['smtp_user'] = 'user@gmail.com'; //change this
    $config['smtp_pass'] = 'password'; //change this
    $config['mailtype'] = 'html';
    $config['charset'] = 'iso-8859-1';
    $config['wordwrap'] = TRUE;
    $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
?>

The above is the smtp settings for gmail. The 'smtp_user' is your (gmail) email id and 'smtp_pass' is the email password.

Next we have to load the codeigniter email library and use its methods to send mail.

Code to Send Email in Codeigniter using Gmail

Use this sendmail() function in a controller file to send email. You can load the 'email' library either inside the function or in the controller constructor.

<?php
//send mail
function sendmail()
{
    $this->load->library('email'); // load email library
    $this->email->from('user@gmail.com', 'sender name');
    $this->email->to('test1@gmail.com');
    $this->email->cc('test2@gmail.com'); 
    $this->email->subject('Your Subject');
    $this->email->message('Your Message');
    $this->email->attach('/path/to/file1.png'); // attach file
    $this->email->attach('/path/to/file2.pdf');
    if ($this->email->send())
        echo "Mail Sent!";
    else
        echo "There is error in sending mail!";
}
?>

All the above email methods like from(), to() are pretty self explanatory and I'll leave it to you. The method $this->email->send() will return a boolean value based upon if email is sent or not.

If you want to send mail in bulk, use comma separated email-id's in $this->email->to() method like this.

$this->email->to('test1@gmail.com, test2@gmail.com, test3@gmail.com');

Also Read:

That's all about sending email in codeigniter via smtp.

Last Modified: Mar-03-2017

Twitter Bootstrap Search Box with Icon in NavBar Example

On 3/03/2017 Be the first to comment!

Hi, we'll see how to add icon to search box in twitter bootstrap in this tutorial. It's just one of the unspoken rules of modern web design to include search box on every websites and blogs out there. Especially for content rich sites, having a search box on top will help the users to dig out the archives for the right information. Generally including a search bar on a website's top navigation menu is easy on the eyes. I am not going to discuss here about adding a search bar on bootstrap's navigation bar. As that topic had been already covered in this bootstrap navbar tutorial.

Typically adding a text box along with a search button may just fills out the purpose of a search box but it's sort of old school. So either we can go off without a visible submit button or with a search icon at the end of the search box. We'll better stick on to the latter option here.

Also Read:

The challenge here is to add a clickable search icon to the end of the search bar that looks great and properly aligned on both desktop and mobile screens. So the best way is to append the icon to the search textbox. In simple terms my idea is to create a bootstrap search box that looks something like this.

bootstrap-search-box-with-icon
Bootstrap Search Box

Bootstrap provides an add-on component called "input-group" that can be used to extend text-based input controls by adding text or buttons before, after or on both sides of the form control.

We are going to use this "input-group" add-on to add a submit button at the end of the text box in the search bar. But the submit button will hold a search icon (from glyphicons) instead of text and by this way we get a clickable icon.

Twitter Bootstrap Search Box with Icon in Navbar:

Let's see how to create bootstrap search box with icon in navbar. You need to load both bootstrap's css and js files in the html file for the navigation menu to work. The bootstrap javascript file is required to show and hide the menu section when navbar is collapsed on devices with smaller screens (like tablet, mobiles).

1. First make the web page responsive by adding this meta tag to the html file.

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

2. Next include the bootstrap css file within the <head></head> section of the html.

<link href="/path/to/bootstrap.css" rel="stylesheet" type="text/css" />

3. Load the bootstrap javascript and jquery library just above the closing body (</body>) tag.

<script src="/path/to/jquery-1.10.2.js"></script>
<script src="/path/to/bootstrap.js"></script>

Just make sure you load jquery file before bootstrap js file for it to work.

Note: I have included the non-minified versions of css and js files as this is for development. But remember to use minified versions on production environment.

4. Finally add the bootstrap navbar component itself. Here we add the logo and the menu items to the left of the navigation menu and the search box at the right side.

<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <!-- add header -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">TravelZ</a>
        </div>
        <!-- add menu -->
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Services</a></li>
            </ul>

            <!-- add search form -->
            <form class="navbar-form navbar-right" role="search">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="Search this site">
                    <span class="input-group-btn">
                        <button type="submit" class="btn btn-default">
                        <span class="glyphicon glyphicon-search"></span>
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>
</nav>

This markup will create a responsive navigation menu that looks best in both desktop and mobile view. Now this is how the navbar will look like.

twitter-bootstrap-navbar-desktop-view
Desktop View - Bootstrap Navbar Search Box with Icon

twitter-bootstrap-navbar-mobile-view
Mobile View - Bootstrap Navbar Search Box with Icon

From the above code, you can see we have created bootstrap inverse navbar with some menu items and search box with icon. Adding "navbar-right" class to the search form aligned it to the right side of the navbar element. To append the submit button to the textbox, we have wrapped up the <button></button> element inside the ".input-group-btn" class.

Also Read:

That's all about creating bootstrap search box with icon in navbar.

Last Modified: Mar-3-2017

Contact Form

Name

Email *

Message *