Activating the search feature on Bootstrap by clicking in the

I recently implemented the following Bootstrap 4 HTML structure for a search feature:

    <div class="col-sm-3 col-md-3 search-header">
    <form class="navbar-form" role="search">
        <div class="input-group">
            <input type="text" class="form-control search-box " placeholder="Search" name="srch-term" id="srch-term">
            <div class="input-group-btn">
                <button class="btn btn-default btn-search" onclick="ss()"><i class="glyphicon glyphicon-search"></i></button>
            </div>
        </div>
    </form>
</div>

However, I'm facing an issue where clicking the search button causes the entire page to refresh. Despite adding an OnClick() event bound to a custom function (ss()) which only triggers an alert, the form still refreshes.

I am now looking to bind the search button to a JavaScript function that will handle the actual search functionality. How can I achieve this?

Answer №1

function greet(){
alert("hello!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-3 col-md-3 search-header">
    <form class="navbar-form" role="search">
        <div class="input-group">
            <input type="text" class="form-control search-box " placeholder="Search" name="srch-term" id="srch-term">
            <div class="input-group-btn">
                <button class="btn btn-default btn-search" onclick="javascript:greet()"><i class="fa fa-search"></i>search</button>
            </div>
        </div>
    </form>
</div>

Answer №2

Give this a shot. Make sure to include a return false statement in your JavaScript function and use the return keyword before calling your function.

function ss(){
alert("hiiiii");
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-3 col-md-3 search-header">
    <form class="navbar-form" role="search">
        <div class="input-group">
            <input type="text" class="form-control search-box " placeholder="Search" name="srch-term" id="srch-term">
            <div class="input-group-btn">
                <button class="btn btn-default btn-search" onclick="return ss();"><i class="fa fa-search"></i>search</button>
            </div>
        </div>
    </form>
</div>

If you prefer using Jquery, consider looking into the event.preventDefault() method for achieving the same results.

Answer №3

Below is the code snippet:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
    </style>
</head>

<body>
    <div class="col-sm-3 col-md-3 search-header">
        <form class="navbar-form" role="search">
            <div class="input-group">
                <input type="text" class="form-control search-box " placeholder="Search" name="srch-term" id="srch-term">
                <div class="input-group-btn">
                        <button class="btn btn-default search" onclick="return myFunction()">Click me</button><i class="glyphicon glyphicon-search"></i></button>
                </div>
            </div>
        </form>
    </div>
<script>
function myFunction() {
   alert ("hiiiiiiiiiiii");
   return false;
}

</script>
</body>

</html>

Answer №4

To enhance performance, consider eliminating the inline onclick attribute and opt for a listener on the button instead:

var btn = document.querySelector('button'); // Using a unique `id` for the button is advisable

btn.addEventListener('click', ss);

function ss(){
    alert('hello');
}

To prevent page reloading, utilize preventDefault rather than return false in conjunction with the code snippet below:

    var btn = document.querySelector('button'); // Opt for a unique `id` for the button to target specifically
    
    btn.addEventListener('click', ss);
    
    function ss(e){
        alert('hello');
        e.preventDefault();
    }
<form class="navbar-form" role="search">
    <div class="input-group">
        <input type="text" class="form-control search-box " placeholder="Search" name="srch-term" id="srch-term"/>
        <div class="input-group-btn">
            <button class="btn btn-default btn-search"><i class="glyphicon glyphicon-search"></i></button>
        </div>
    </div>
</form>

jsFiddle: https://jsfiddle.net/AndrewL64/n7s90pgt/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap 4 split buttons are having issues with proper display

I am encountering several challenges with Bootstrap4 and split buttons. My goal is to create a versatile button that can perform different actions based on user selection from a dropdown menu. The split button functionality seemed like an ideal choice for ...

Customize the keyboard on your iPod by replacing the default one with a

Looking to customize the iPOD keyboard to only display numbers, similar to a telephone keypad: https://i.stack.imgur.com/X0L3y.png The current iPOD default keyboard looks like this: https://i.stack.imgur.com/VykjU.png ...

Implementing a filter on axios response

Looking to filter the response from Axios? I need to be able to filter and retrieve the filtered response in the browser. The database being used is MongoDB... const getNodeData = (route, params) => new Promise((resolve, reject) => axios.g ...

Chrome on Android experiences freezing issues with React.js mobile sites

We are currently experiencing an issue with our React.js website on Chrome/Android. This problem does not seem to occur on other browsers or platforms, as desktop performance is consistently smooth. The issue appears to be related to the front page, possi ...

How can I ensure that my columnar div box is responsive on smaller devices with CSS or should I consider using Bootstrap?

I have a container with a row that contains multiple div boxes. Currently, I am using CSS to spread these div boxes into 3 columns using the column-count property. I have a few questions: 1) How can I make this responsive for smaller devices? 2) Can I ...

Unpacking Objects in JavaScript and TypeScript: The Power of Destructuring

I have a variable called props. The type includes VariantTheme, VariantSize, VariantGradient, and React.DOMAttributes<HTMLOrSVGElement> Now I need to create another variable, let's name it htmlProps. I want to transfer the values from props to ...

No response observed upon clicking on the li element within the personalized context menu

I created a custom context menu that pops up when you click on an li element within an unordered list. I'm trying to trigger an alert when clicking on an li item inside the context menu, but it's not working as expected. To handle this dynamic c ...

Combining Ng-model with iOS credit card scanning functionality offers a seamless and

Dealing with Ng-model and iOS credit card scanning In my credit card form, each field is structured like this: <input type=“text” ng-model = “cc.number”, ng-class = validClass('cc.number’)> The function validClass returns either val ...

Are JavaScript comments posing a security threat?

During a recent PCI audit, the auditor identified what they believed to be major security risks in our system: The ability to download static resources such as images, CSS, and JavaScript from our website without authentication The presence of comments i ...

What is the best way to include a href link with parameters retrieved through an API in a React application

I am currently working on a frontend project using react. My goal is to include a link to the survey page after generating a map based on data retrieved from an API. However, I am facing two main challenges: Firstly, I am unsure about how to add paramet ...

The build process encountered an error due to the absence of ESLint configuration after the import

Having recently worked on a Vue project created using Vue CLI, I found that eslint was also included in the project. Although I haven't utilized eslint much up to this point, I understand that it is beneficial for catching stylistic errors, semantic e ...

It appears that the React State is getting overridden or the setState function is not functioning properly

Hello, I’ve been diving into React lately and I feel like I might be missing a key concept when it comes to updating state and rendering components. const allFalse = new Array(data.length) const allTrue = new Array(data.length) allFalse.fill(false) ...

Navigate through inner divs on iOS using VoiceOver by performing a 3-finger swipe up or down

I'm currently experimenting with VoiceOver and scrolling, specifically the three-finger swipe up/down gesture on my test page located at: http://107.170.41.208/AccessibleHTML The test page consists of a div with scrollable content (red background) f ...

Learning the basics of JavaScript: Displaying the last number in an array and restarting a function

Hey there, I'm diving into the world of JavaScript and have set myself a challenge to create a simple bingo number machine. Check out my CodePen project here. I've successfully generated an array of 20 numbers, shuffled them, and added a marker t ...

Why does Typeahead display a JSON object in the input field upon clicking?

My suggestion engine is working well, but I am facing an issue where the json object appears in the input element when I click on an item. I want only the OrgName to show up in the input value. <input class="form-control companySearch" type="text" valu ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

Is it possible for this solution to be compatible with IE7 and IE6?

Is there a way to enhance this solution for compatibility with IE6 and IE7? http://jsfiddle.net/kirkstrobeck/sDh7s/1/ Referenced from this discussion After some research, I have come up with a practical solution. I've converted it into a new func ...

Leveraging Javascript variables in console.log for referencing purposes

I have recently started learning JavaScript and I have a query regarding the usage of variables in the Console.log function. What could possibly cause an error in this code snippet? var myAns = console.log(65/240); console.log( ...

Function not currently in operation

There seems to be an issue with the script not running or returning any answers. The console is blank. I am attempting to retrieve an answer from the Yandex Translate site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) Code: http: ...

Using jQuery AJAX in ASP.NET to invoke a controller's method

Seeking assistance with jQuery AJAX implementation in a View to call a Controller's action. The task involves validating an email address from two input boxes: "Email Address" and "Email Password". The intention is to display the result in a "div" loc ...