Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align.

That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the classes: about, portfolio, and contact. The about container is visible while the other two are hidden.

What I'm trying to achieve is when I type certain words into a text box (or search box), such as "portfolio" or "portofoliu," and press enter, the about container will fade out and the portfolio container will fade in. The same effect should happen between about and contact.

I'm unsure how to implement this... Can anyone help? If you have a solution ready, providing a fiddle would greatly assist me in understanding how it functions.

Thank you

PS: One function that comes to mind is jQuery's .is() - comparing two elements. However, I'm not sure how to use it to compare with the text in the textbox.

I attempted the following code but it didn't work:

$("#portfolio").hide();
$("#wrong").hide();

$('#search').keyup(function() {
    if ($("#portfolio").is("#search")) {

    $("#portfolio").fadeIn();

}else{
    $("#wrong").fadeIn();
}
});

JSFIDDLE

Answer №1

Experiment

hypertext markup language

<input id="search" type="text" />
<div id="content">
    <div id="about">about
        <br /><i>about content</i>
    </div>
    <div id="portfolio">portfolio
        <br /><i>portfolio content</i>
    </div>
    <div id="contact">contact
        <br /><i>contact content</i>
    </div>
</div>

javascript

var substringMatcher = function (strs, q, cb) {
    return (function (q, cb, name) {
        var matches, substrRegex;
        // an array that will be populated 
        // with substring matches
        matches = [];
        // regex used to determine if a string 
        // contains the substring `q`
        substrRegex = new RegExp(q, 'i');
        // iterate through the pool of strings 
        // and for any string that
        // contains the substring `q`, 
        // add it to the `matches` array
        $.each(strs, function (i, str) {
            $("#search").val("");
            if (substrRegex.test(str) 
               || q.slice(0, 1) === str.slice(0, 1)) {
                // the typeahead jQuery plugin 
                // expects suggestions to a
                // JavaScript object, refer to 
                // typeahead docs for more info        
                matches.push(name(str));
            }
        });
        cb(matches);
    }(q, cb, function (n) {
        return {
            "content": n
        }
    }));
};

var _matches = $.map($("#content div"), function (v, k) {
    return [v.id]
});

var template = {
    "content": _matches
};
$("#content div:gt(0)").hide(0);
$('#search').focus().keyup(function (e) {
    var search = $(this);
    var _search = search.val();
    if (e.which === 13) {
        substringMatcher(template.content, _search, function (d) {
            $("#" + d[0].content).fadeIn(500).siblings().hide();
            search.val("");
        })
    }
});

link to jsfiddle http://jsfiddle.net/guest271314/2na7dyjf/

For further reference, visit typeahead.js - examples

Answer №2

Check out this jsFiddle demo

To apply a hidden class to all your DIV elements, use the following code:

<div class="hidden" id="portfolio">Hello</div>
<div class="hidden" id="wrong">Not quite</div>

Now, try this script:

$(".hidden").hide();

var searchID = "";

$('#search').keyup(function( e ) {
    searchID = $.trim( this.value.toLowerCase() );
    if( searchID && e.which===13){
       $(".hidden").hide();
       $('[id='+  searchID  +']').show();
    }
});

Note: For case-insensitive targeting of the ID, add .toLowerCase() within the selector.

If you want to make the selection less stringent, explore other selectors like:

[id*=  Contains...
[id^=  Starts With...
[id$=  Ends With...

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

What is the best approach for selecting and organizing MongoDB records, as well as identifying the following record for retrieval?

Currently, I have a stack of documents that needs to be filtered out based on specific criteria and then arranged alphabetically according to the string value within those documents — let's call it a "search result". Subsequently, I am required to l ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

The issue at hand is that the headers cannot be redefined once they have already been sent

Hello, I have tried numerous solutions but have not been able to resolve the "Can't set headers after they are sent" error in the following simple code. I have spent several days working on this and would greatly appreciate any input you may have. ap ...

The case of the elusive Firefox overflow: hidden glitch

Recently, I integrated an image slider into my web design and it displayed perfectly on Internet Explorer and Chrome. However, when viewed on Firefox, I encountered a strange problem where the images in the slider were being pushed towards the right side o ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

Can you explain the distinction between sockets and proxy passing in nginx compared to uwsgi?

My latest project setup involves flask, uwsgi, and nginx. The backend solely serves json data through an API, while the client side takes care of rendering. Typically, my Nginx configuration looks like this: My usual setup (with basic proxy passing): se ...

Utilize setState in a ReactJS function within an if statement towards the end

Help needed! I'm facing issues trying to use the function setState within an if statement inside another function. Specifically, I'm working on creating a series of Tab components with inline styles that determine their visibility. Before returni ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

Is there a way to retrieve the text content of the element that has been clicked?

code: <script> $(document).ready(function(){ $(".special").click(function(){ courses = this.id; location.href = "courses-college.php?courses="+courses; }); }); </script> <ul> <li class= ...

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

What seems to be causing the malfunction in this ranking function?

I created a custom function to retrieve the top five users from a JSON database. Below is the code snippet: var users = []; Object.keys(database).forEach(user => { if (!users[0]) { users[0] = user } else { var checked = false; for (let ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

Angular's isteven-multi-select Component: A Versatile Selection Tool

Is it possible to utilize isteven-multi-select with ng-model? My goal is to have certain items appear as chosen when the page loads using the isteven-multi-select module. I've tried using ng-model in the HTML page to populate the isteven-multi-select ...

Sending emails to multiple groups in Opencart can be easily achieved with the

I am interested in customizing Opencart's admin panel to allow for the selection of multiple customer groups when sending emails. However, I am unsure of where and how to make these modifications as I am relatively new to this type of task. ...

What could be causing issues with the JQuery .Resize() function?

I'm attempting to create a responsive layout where the content div adjusts itself when the user resizes the page. The top and bottom divs are static, so only the content div changes its size based on the page flow. $(window).resize(function() { v ...

The jQuery focusout event is triggered on a form element, even if a child element is clicked within the form

How can I ensure that the focusout event is triggered only when the user is not focusing on the entire form element? Currently, if the user clicks on any of the form's inner elements such as the text field or the button, the event is still being trigg ...

[ERROR_HTTP_HEADERS_ALREADY_SENT]: Headers can't be set once they have been sent to the client, expressjs

Whenever I attempt to insert data into my MySQL database using the express router function, I encounter an error. It appears that my server is trying to send a response twice, but I am unsure of where the issue lies. Here is the error message: throw err; / ...