settingsAccountsettings
Menusettings

Q: Search in List (task with DOM and jQuery)

+3 votes

An HTML page holds a list of towns, a search box and a [Search] button. Implement the search function to bold the items from the list which include the text from the search box. Also print the amount of items the current search matches in the format "<matches> matches found."

HTML and JavaScript Code - You are given the following HTML code:
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search in List</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
    <script src="search.js"></script>
</head>
<body>
<ul id="towns">
    <li>Sofia</li>
    <li>Pleven</li>
    <li>Varna</li>
    <li>Plovdiv</li>
</ul>
<input type="text" id="searchText" />
<button onclick="search()">Search</button>
<div id="result"></div>
</body>
</html>

Examples:

search in list jquery

asked in JavaScript category by user icabe

1 Answer

+2 votes

My HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <!--<script src="src/jquery-3.2.1.min.js"></script>-->
    <script src="src/search.js"></script>
</head>
<body>
<ul id="towns">
    <li>Sofia</li>
    <li>Pleven</li>
    <li>Varna</li>
    <li>Plovdiv</li>
</ul>
<input type="text" id="searchText"/>
<button onclick="search()">Search the towns</button>
<div id="result"></div>

</body>
</html>

JavaScript code + jQuery code:

function search() {
    let searchText = $('#searchText').val();
    let matches = 0;
    $("#towns li").each((index, item) => {
        if (item.textContent.includes(searchText)) {
            $(item).css("font-weight", "bold");
            matches++;
        } else
            $(item).css("font-weight", "");
    });
    $("#result").text(matches + " matches found.");
    $("#searchText").val("");
}

 

answered by user john7
...