snow snow - 1 year ago 96
Javascript Question

javascript: Implement an instant search functionality

I want to implement a functionality in my wikipedia app which gives the user two options:

  • an option to do an instant search, i.e. get results as the user types in the search box

  • an option to do a normal serach upon hitting
    . i have a button to toggle that functionality. Below is the JS code:

    var btn = $(".autocomplete-button .btn");

    function searchOptions() {

    btn.html() === "Instant Results Off" ?
    btn.html("Instant Results On") :
    btn.html("Instant Results Off");

    if( btn.html() === "Instant Results On") {
    } else {

    function advancedSearch() {




    function onSubmit(){

    $(".search-form").submit(function(e) {


You can test out the app here: Codepen

Problem: The default search method is a normal search. Once i turn the
instant search on
the app always does an instant search no matter what the current setting is.

What have i tried? i assumed the
function keeps running regardless of what setting the button displays. Therefore i included a conditional to
the function whenever the button is clicked. But that didn't solve anything.

Please note the console messages. the console.log statements that i have placed in each function clearly convey that the
function is correctly not being triggered when the instant search button is set to off and thats what makes this behavior so puzzling to me.

any solutions to this problem will be appreciated. I will change the title of the qn once the reason of the problem will be known. Thank you for your patience.

Answer Source

Just add a switch variable like this:

var liveSearchSwitch = 0;

and, make some simple logic changes.

OK, I made it:

You can see the difference with JavaScript code and mine here:

Please let me know if you couldn't get what I did

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download