Word search with span element count - javascript

I'm working on making a word search for whatever word is entered into the input box. I'm trying to create a div element that would show a string consisting of all words found at least once in each paragraph, for successive searches, below the input box. I also want to create a span element that maintains a count of the words that are found in all paragraphs for all searches. I'm just pretty lost with all of it and unsure where to even start.
/*window.onload = function()
{
document.getElementById("searchbutton").onclick = searchClick;
};
I needed to bring this one line lower to work on commenting out */
but1 = document.querySelector("#searchbutton");
but1.addEventListener('click', searchClick);
// Called when the Search button is clicked.
// Looks for paragraphs matching a search string and highlights them.
function searchClick() {
var searchPhrase = document.getElementById("searchtext").value;
/*var main = document.querySelector("#main");*/
var mainParas = document.getElementsByTagName("p");
for (var i = 0; i < mainParas.length; i++) {
if (mainParas[i].textContent.indexOf(searchPhrase) >= 0) { mainParas[i].className = "highlighted"; } // highlight
else {
mainParas[i].className = null; // un-highlight
}
}
}
<body>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in
Phoenix, Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an
expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an
ownership group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
</div>
<p>Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.</p>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton">Search</button>
</div>
</body>

Your problem seems to be that document.querySelector("#searchbutton") returns null so that but1.addEventListener('click', searchClick); fails. Instead of searching for the reason I skipped adding a listener and directly attached the onclick function with
<button id="searchbutton" onclick="searchClick()">Search</button>
in the html. This worked, but I had to define a css rule for highlighting that wasn't posted in your code.
Edit 01.05.2021 - I didn't cover counting the matches, so here it is completely:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
p.highlighted { background-color: Yellow; }
</style>
</head>
<body>
<body>
<script type="text/javascript">
function searchClick() {
var count = 0;
var searchPhrase = document.getElementById("searchtext").value;
var mainParas = document.getElementsByTagName("p");
for (var i = 0; i < mainParas.length; i++) {
if (mainParas[i].textContent.indexOf(searchPhrase) >= 0) {
mainParas[i].className = "highlighted"; // highlight
count += mainParas[i].textContent.split(searchPhrase).length - 1;
} else {
mainParas[i].className = null; // un-highlight
}
}
document.getElementById("found").textContent = count + " matches found";
}
</script>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix, Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
</div>
<p>Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.</p>
<hr />
<div>Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton" onclick="searchClick()">Search</button>
<span id="found"></span>
</div>
</body>
</html>
The counting happens with the loop checking the paragraphs. Before, a variable count is defined, inside it gets increased if matches occur, and after the loop the span id="found" is updated with the value of that variable.
For counting matches of the phrase and not numbers of paragraphs with matches, the text content is split up using the search phrase as delimiter. Then the number of pieces minus one is the number of occurences. Counted are phrases, not words. The phrase "the" is found in both " the " and " they ", but not in "The". Case sensitivity wasn't asked and isn't hard to implement. Just uppercase both the search phrase and the text being searched.
For simplicity, I put together HTML, Javascript and CSS into one file.

Related

How to count times of appearance of a certain word in a div full of text in JavaScript?

I am trying to create an event function that's associated with a button that, when clicked after you input a phrase into the text area, counts how many times this phrase has appeared in the text (only the p elements) and simultaneously output the value (how many times) into a span element that this function creates.
The intended result is this:
enter image description here
This is my html:
<body>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix,
Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an
expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership
group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
</div>
<p>
Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.
</p>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton">Search</button>
</div>
</body>
And this is my js function:
function count_search(event){
let span = document.createElement('span');
span.setAttribute("id", "output");
document.body.appendChild(span);
var searchPhrase = document.querySelector("#searchtext").value;
var main = document.querySelector("#main");
var mainParas = main.querySelectorAll(" p ").textContent;
document.getElementById("#output").innerHTML =
(mainParas.match(/searchPhrase/g)).length;
/*var times = (mainParas.match(/searchPhrase/g) || []).length;
var content = "Searched for the word '" + searchPhrase + "' for " + times + "
times. ";
document.getElementById("output").innerHTML = content; */
}
However, the result just won't show. Can you please help me? Any suggestion is much appreciated!
<body>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix,
Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an
expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership
group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
</div>
<p>
Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.
</p>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton" onClick="count_search()">Search</button>
</div>
<script>
function count_search(event){
span = document.createElement('span');
span.setAttribute("id", "output");
document.body.appendChild(span);
var searchPhrase = document.querySelector("#searchtext").value;
searchPhrase = new RegExp(searchPhrase, 'g');
var main = document.querySelector("#main");
let count = 0;
var mainParas = main.querySelectorAll("p").forEach(ele => {
const times = ele.innerHTML.match(searchPhrase);
count += times ? times.length : 0;
});
span.innerHTML = count;
}
</script>
</body>
So the reason it was not showing up before is cause there was no onclick event associated with the button. The following code should help in a way.
This code may help you. It takes all child elements of type p of the main div, takes their contents and concatenates them into a single string.
Then it searches this string for the word entered into the input field and returns the number of ocurrences.
Word search is done using a regular expression with two modifiers: g to let the search continue after the first match and i to ignore capitalization.
Notice how it returns 2 when you enter 'dolor', because the third ocurrence of dolor is in a lielement, not a p.
function search() {
// Get the word to count
var searchString = document.getElementById("input").value;
var textDiv = document.getElementById("main");
// Get all p elements in the main div
var childNodes = textDiv.getElementsByTagName('p')
// Store all text from the child elements in a single string
var completetext = ""
for(var i = 0; i < childNodes.length; i++) {
completetext = completetext + childNodes[i].innerHTML
}
// Search the string and count the ocurrences
var regEx = new RegExp(searchString, "gi");
// When match() returns 0, replace it with an empty array
// to make the length work in this case
var count = (completetext.match(regEx) || []).length
result.innerHTML = count;
}
<div id="main">
<p>Lorem ipsum dolor sit amet. Lorem ipsum</p>
<p>Lorem ipsum dolor sit amet. Lorem ipsum</p>
<li>dolor sit amet.</li>
</div>
<input type="text" id="input">
<button id="button" onclick="search()">Search</button>
<span id="result">
Here is some JS that does this
function count_search(event){
let span = document.createElement('span');
span.setAttribute("id", "output");
document.body.appendChild(span);
var searchPhrase = document.querySelector("#searchtext").value;
var main = document.querySelector("#main");
var mainParas = main.querySelectorAll("p");
mainParas = Array.from(mainParas)
for (let i = 0; i<mainParas.length;i++) {
mainParas[i] = mainParas[i].textContent
}
mainParas = mainParas.join(' ')
words = mainParas.split(' ')
count = 0;
for (let i = 0; i<words.length;i++) {
if (words[i] == searchPhrase) {
count++
}
}
document.getElementById("output").innerHTML = count
}
You are almost on the right way. Once you have all the p's in the main div you can iterate over them in order to get its text. Then you could append to a string that contains all the texts so you could search in it after. For that, create a RegExp with the value you want to search, finally use match() to find out the times the string is in the text.
function count_search() {
var allText = "";
var element = document.getElementById("output");
element && element.parentNode.removeChild(element);
let span = document.createElement('span');
span.setAttribute("id", "output");
document.body.appendChild(span);
var searchPhrase = document.querySelector("#searchtext").value;
var mainParas = document.querySelectorAll("#main > p");
mainParas.forEach(el => allText+= el.innerText);
var regex = new RegExp(searchPhrase, "gi");
var times = allText.match(regex);
document.getElementById("output").innerHTML = times ? `How many times I searched for the word "${searchPhrase}": ${times.length}` : "No matches found";
}
<body>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix,
Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an
expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership
group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
</div>
<p>
Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.
</p>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton" onclick="count_search()">Search</button>
</div>
</body>

Debugging Show More Show Less button - Missing Paragraphs of Text

There a 'load more/load less' function running on this page which I'm attempting to debug. https://maes-mynan.cogitoprojectx.com/holiday-homes/the-llewellyn-lodge-lodge/
You can see it the section with the heading "More About The Llewellyn Lodge"
The text is displayed via an Advanced Custom Fields WYSIWYG field [WordPress].
I've been playing around with numbers in lines i.e. .length>4 with no effect.
As far as I can see, the code is set to truncate the text after the fourth paragraph and on-click show the full text. However, instead of just truncating the text, it seems to remove the fourth paragraph entirely.
In essence, it displays paragraphs 1 - 3, [misses 4] and then displays paragraph 5 onwards.
I've been changing the value of the number in line e.g. .length>4 with no effect.
Any help, to stop the paragraph disappearing entirely will be gratefully appreciated.
jQuery(document).ready(function() {
jQuery('.read-more2').each(function() {
if (jQuery(this).children('p').length > 4) {
jQuery(this).children('p:lt(3)').show();
jQuery(this).append('<button class="loadMore btn btn-primary">Show More</button>');
}
});
jQuery('.read-more2').on("click", '.loadMore', function() {
jQuery(this).parent('.read-more2').children('p:gt(3)').show(); // use gt instead of lt
jQuery(this).removeClass('loadMore').addClass('loadLess').text('Show Less');
});
jQuery('.read-more2').on("click", '.loadLess', function() {
jQuery(this).parent('.read-more2').children('p:gt(3)').hide(); // use gt instead of lt
jQuery(this).removeClass('loadLess').addClass('loadMore').text('Show More');
});
});
Assuming the reason for SHOWING initially is that all p's are hidden, we need to hide the gt(2) when we toggle.
the code could be shortened by having the button use .toggle(this.textContent==='Show More') instead of having two event handlers and two class names
$(document).ready(function() {
$('.read-more2').each(function() {
if ($(this).children('p').length > 4) {
$(this).children('p:lt(3)').show(); // because they were hidden
$(this).append('<button class="loadMore btn btn-primary">Show More</button>');
}
});
$('.read-more2').on("click", '.loadMore', function() {
$(this).parent('.read-more2').children('p').show(); // use p to show all
$(this).removeClass('loadMore').addClass('loadLess').text('Show Less');
});
$('.read-more2').on("click", '.loadLess', function() {
$(this).parent('.read-more2').children('p:gt(2)').hide(); // use gt 2 instead
$(this).removeClass('loadLess').addClass('loadMore').text('Show More');
});
});
.read-more2 > p { display:none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="read-more2">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
</div>
<div class="read-more2">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<p>p5</p>
<p>p6</p>
</div>
$(document).ready(function() {
$('.read-more-spec').each(function() {
if ($(this).find('ul li').length > 4) {
$(this).find('ul li:lt(3)').show(); // because they were hidden
$(this).append('<button class="loadMore btn btn-primary">Show More</button>');
}
});
$('.read-more-spec').on("click", '.loadMore', function() {
$(this).parent('.read-more-spec').find('ul li').show(); // use p to show all
$(this).removeClass('loadMore').addClass('loadLess').text('Show Less');
});
$('.read-more-spec').on("click", '.loadLess', function() {
$(this).parent('.read-more-spec').find('ul li:gt(2)').hide(); // use gt 2 instead
$(this).removeClass('loadLess').addClass('loadMore').text('Show More');
});
});
.read-more-spec ul li { display:none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6 read-more-spec black">
<h3>LODGE FEATURES</h3>
<div>
<ul>
<li>Vaulted ceiling to lounge, kitchen and diner</li>
<li>Two sets of French doors to the front elevation</li>
<li>Overhanging eaves with discreet lighting to the external front elevation</li>
<li>Colour coordinated curtains, blinds and carpets</li>
<li>Fully fitted country style kitchen with four burner gas hob, built under oven and integrated dishwasher and fridge/freezer</li>
<li>Centre island/breakfast bar with two high backed chairs</li>
<li>Utility cupboard with under counter washing machine, condensing dryer, hooks, shelves and boot drying area under boiler</li>
<li>Solid wood dining table top with four painted white chairs</li>
<li>One large comfortable sofa and two armchairs – both in a classical design</li>
<li>Coffee table and lamp table also feature in the lounge area</li>
<li>Fireplace mantel and, electric log burner style fire</li>
<li>5ft King sized bed in master bedroom with gas lift under-bed storage</li>
<li>Freestanding bedroom furniture which includes large wardrobe, mirror, dressing table, dressing stool and bedside tables</li>
<li>Ensuite bathroom with tiled corner shower and heated towel rail</li>
<li>Bath in main bathroom with overhead shower and heated towel rail</li>
<li>Wall mirrors in both bathrooms</li>
<li>TV points in lounge and master bedroom</li>
<li>Energy efficient A Rated boiler with radiators and central heating throughout</li>
<li>Built to British Standard 3632 – residential specification</li>
<li>Timber frame structure</li>
<li>10 year structural warranty</li>
<li>Horizontal Sierra Canexel Cladding to the exterior for easy maintenance</li>
<li>Anthracite grey UPVC double glazed doors and windows</li>
<li>Large decking in complementing grey composite board and handrail with two lockable gates (ideal for dog owners) to front and side. Steps down into the side garden area</li>
<!-- <button class="loadMore btn btn-primary">Show More</button> -->
</ul>
</div>

How do I simultaneously filter the answer section that is associated with the questions?

I have been able to filter the questions. But how do I also filter the answers associated with each question simultaneously?
This is the HTML
<input style="text-align: center" type="text" id="myInput" onkeyup="myFunction()" placeholder="What would you like to know?" title="Type in a name">
</span>
<p class="example"><span>What is a "four season" sunroom?</span> </p>
<p class="answer">A traditional sunroom is usually treated more like an outdoor enclosure than a home addition, because it is designed only for seasonal use during mild weather. In contrast, a four season sunroom is more like adding a new room to your home, by incorporating
heavily insulated materials to keep it comfortable even during the extremes of winter and summer. A “true” four season sunroom should feel like an extension of your home and is easy to keep conditioned and comfortable.</p>
</span>
<p class="example"><span>What is a conservatory</span> </p>
<p class="answer">The terms sunroom and conservatory are often used interchangeably, but there are some informal differences. A conservatory typically has a larger percengtage of glass included in the walls than a sunroom does. Also, a conservatory almost always has a
glass roof, while most sunrooms have a traditional solid roof. Conservatories are common in Europe.</p>
</span>
<p class="example"><span>What sunroom styles are there</span> </p>
<p class="answer">LivingSpace offers four different types of sunrooms: the Cathedral Sunroom, the Studio Sunroom, the Integrated Sunroom, and the Specialized Sunroom. Further information on them can be found <b>here</b>.
</p>
This is the javscript
function myFunction() {
var input, toUpper, ul, question, span, i;
answer = document.querySelector(".answer");
input = document.getElementById("myInput");
toUpper = input.value.toUpperCase();
question = document.getElementsByClassName("example");
for (i = 0; i < question.length; i++) {
span = question[i].getElementsByTagName("span")[0];
if (span.innerHTML.toUpperCase().indexOf(toUpper) > -1) {
question[i].style.display = "";
} else {
question[i].style.display = "none";
}
}
}
Here is the codepen
https://codepen.io/mfahad24/pen/wxQaPz

Show/hide list items based on search value

I have the following list which is brought through AJAX, each 'li' haves a default 'display: none' value (the list haves 800 'li' so here I cut it to show only 3):
Basically I need that when somebody types a value in a search field to go through that whole list comparing that value with the 'h3 > a' text inside each list, so lets say somebody type "Florida" if it's inside an 'h3 > a' show it, the rest keep it hidden.
Also when somebody change the search value for example to "California" it should go again through all the list, hiding the actual ones (in this case "Florida") and showing the ones that haves "California" text in their h3 > a.
Thank you!
<form method="post" action="/employers/">
<fieldset>
<legend>Employer search</legend>
<div class="field">
<label for="searchtext" class="hidden">Search employers</label>
<div class="clear-input js-clear-input">
<input id="searchtext" type="text" name="RecruiterName" value="Florida" placeholder="Start typing…" class="clear-input__input js-recruiter-lookup js-clear-input-input" autocomplete="off">
<i data-icon="x" class="clear-input__trigger icon-before js-clear-input-trigger" style="display: inline;"></i>
</div>
</div>
<div class="field">
<select name="RecruiterTypeId" class="js-recruiter-type">
<option value="">All</option>
<option value="-10">Employer</option>
<option value="-20">Search Firm</option>
<option value="513012">Advertising Agency</option>
</select>
</div>
<input type="hidden" name="RecruiterId" value="" class="js-recruiter-id">
<input type="submit" value="Search" id="search" class="button button--brand">
</fieldset>
</form>
Actual code which is not working (it shows me the whole list):
// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
// Prevent the original click for not reloading the whole page
event.preventDefault();
// Get value from search input #search
var searchInputValue = $('#search').val();
// Search the list and if it matches display it, else hide it
$('.lister__item').each(function() {
var isMatch = $('.lister__item > h3 > a:contains(' + searchInputValue + ')');
$(this).parent().parent().toggle(isMatch);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="search" id="search" />
</div>
<div class="employers-list">
<ul>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American International College<small>
19 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American National University<small>
1 job</small>
</h3>
<p class="no-margin"> In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American University in Dubai<small>
12 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
</li>
</ul>
Actual working code:
// Disable form since we need first the list loaded for being used
$('form').css('display', 'none');
// Get the total amount of pages
var totalPagesCount = $('.paginator__item:last-child a').attr('href').split('/')[2];
// Create a div container for adding future employers list and not being deleted later when the onclick occurs
$('<div />').addClass('employers-list').appendTo('#listing');
// Get every employer from the all the pages
for(var i=0; i<totalPagesCount; i++) {
$.ajax({
url: 'https://careers.insidehighered.com/employers/' + (i+1),
type: 'get',
cache: false,
dataType: "html",
success: function(results) {
// Get all the elements and hide them
var page = $(results).find('.lister__item').hide().detach();
// Add them to the empty 'ul'
$('.employers-list').append(page);
},
complete: function() {
// Everything is loaded so show form again
$('form').css('display', 'inline-block');
}
});
}
$.expr[":"].contains_ci = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
// Prevent the original click for not reloading the whole page
event.preventDefault();
// Empty initial list
$('#listing').children('li').remove();
// Remove the paginator
$('.paginator').remove();
// Get value from search input
var searchInputValue = $('#searchtext').val();
$('.lister__item').hide().find('h3 > a:contains_ci(' + searchInputValue + ')').parents('.lister__item').show();
});
Hide all elements first then show the matched elements
Also I've added contains_ci expression which allows search case-insensitive
$.expr[":"].contains_ci = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
// Prevent the original click for not reloading the whole page
event.preventDefault();
// Get value from search input
var searchInputValue = $('#search').val();
// Search the list and if it matches display it, else hide it
$('.lister__item').hide().find('h3 > a:contains_ci(' + searchInputValue + ')').parents('.lister__item').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="search" id="search" />
</div>
<div class="employers-list">
<ul>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American International College<small>
19 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American National University<small>
1 job</small>
</h3>
<p class="no-margin"> In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American University in Dubai<small>
12 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
</li>
</ul>
I took what you had and used a JavaScript RegExp to construct a case-insensitive expression to match in your content. I'm also using $(this) to target the element in the loop.
// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
// Prevent the original click for not reloading the whole page
event.preventDefault();
// Get value from search input
var searchInputString = $('#searchtext').val();
var regExp = new RegExp(searchInputString, 'i');
// Search the list and if it matches display it, else hide it
$('.lister__item').each(function() {
var isMatch = $(this).find('h3 > a').text().match(regExp);
$(this).toggle((isMatch) ? true : false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchtext" type="text">
<button id="search">Search</button>
<div class="employers-list">
<ul>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American International College<small>
19 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American National University<small>
1 job</small>
</h3>
<p class="no-margin"> In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
</li>
<li class="lister__item cf block js-clickable">
<h3 class="lister__header">
American University in Dubai<small>
12 jobs</small>
</h3>
<img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
<p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
</li>
</ul>
</div>

jQuery UI menu code is not rendering

I am using jQuery UI, I have added links to the javascript files (jquery ui.min, jquery-ui.css) in the (head) section, however when I apply jQuery to the menu (#shMenu) - it doesn't render. What are my doing wrong ?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/jquery-ui.min.css">
<script src="js/jquery-ui.min.js"></script>
</head>
<style>
.highlight{background-color:yellow;
}
#wrapper {
width:500px;
margin:auto;
}
.ui-menu {
width:15em;
}
#cartDiv {
border-style:solid;
border-width:5px;
}
</style>
<body>
<div id = "wrapper">
<ul id = "shMenu">
<li>Super Heroes
<ul>
<li>Hulk</li>
<li>Batman</li>
<li>Spider-Man</li>
</li>Thor</li>
</ul>
</li>
<li>Comic Books
<ul>
<li>Hulk</li>
<li>Batman</li>
<li>Spider-Man</li>
<li>Thor</li>
</ul>
</li>
</ul><br/>
<div id = "accordion">
<h3>Batman</h3>
<div>
A young Bruce Wayne (Christian Bale) travels to the Far East,
where he's trained in the martial arts by Henri Ducard (Liam Neeson),
a member of the mysterious League of Shadows. When Ducard reveals the League's true purpose
-- the complete destruction of Gotham City -- Wayne returns to Gotham intent on cleaning up the city without resorting to murder.
With the help of Alfred (Michael Caine), his loyal butler, and Lucius Fox (Morgan Freeman),
a tech expert at Wayne Enterprises, Batman is born.
</div>
<h3>Thor</h3>
<div>
As the son of Odin (Anthony Hopkins), king of the Norse gods,
Thor (Chris Hemsworth) will soon inherit the throne of Asgard from his aging
father. However, on the day that he is to be crowned, Thor reacts with brutality when the gods' enemies,
the Frost Giants, enter the palace in violation of their treaty. As punishment, Odin banishes Thor to Earth. While Loki (Tom Hiddleston),
Thor's brother, plots mischief in Asgard,
Thor, now stripped of his powers, faces his greatest threat..
</div>
<h3>SpiderMan</h3>
<div>
"Spider-Man" centers on student Peter Parker (Tobey Maguire) who,
after being bitten by a genetically-altered spider, gains superhuman
strength and the spider-like ability to cling to any surface. He vows
to use his abilities to fight crime, coming to understand the words of his
beloved Uncle Ben:
"With great power comes great responsibility."
</div>
<div id = "shTabs">
<ul>
<li>Ironman</li>
<li>Hulk</li>
<li>thor</li>
<li>SpiderMan</li>
</ul>
</div>
<div id = "ironman">
A billionaire industrialist and genius inventor, Tony Stark (Robert Downey Jr.),
is conducting weapons tests overseas, but terrorists kidnap him to force him to build a devastating
weapon. Instead, he builds an armored suit and upends his captors. Returning to America,
Stark refines the suit and uses it to combat crime and terrorism.
</div>
<div id = "hulk">
Eric Bana ("Black Hawk Down") stars as scientist Bruce Banner,
whose inner demons transform him in the aftermath of a catastrophic experiment;
Jennifer Connelly portrays Betty Ross, whose scientific genius unwittingly helps unleash the Hulk;
Nick Nolte plays Banner's brilliant father, who passes on a tragic legacy to his son; and Sam Elliott
portrays the commander of a top-secret military research center.
</div>
<div id = "thor">
As the son of Odin (Anthony Hopkins), king of the Norse gods,
Thor (Chris Hemsworth) will soon inherit the throne of Asgard from his aging
father. However, on the day that he is to be crowned, Thor reacts with brutality when the gods' enemies,
the Frost Giants, enter the palace in violation of their treaty. As punishment, Odin banishes Thor to Earth. While Loki (Tom Hiddleston),
Thor's brother, plots mischief in Asgard,
Thor, now stripped of his powers, faces his greatest threat..
</div>
<div id = "spiderman">
"Spider-Man" centers on student Peter Parker (Tobey Maguire) who,
after being bitten by a genetically-altered spider, gains superhuman
strength and the spider-like ability to cling to any surface. He vows
to use his abilities to fight crime, coming to understand the words of his
beloved Uncle Ben:
"With great power comes great responsibility."
</div>
<div></br>
<div id = "customDialog" title = "custom Dialog">
<p>A random dialog box that contains important information</p>
</div>
Open Dialog<br/><br/>
<script type = "text/javascript">
$('document').ready(function() {
$("#shMenu").menu({
position: {
my: "center top"
at: "center bottom"
};
});
});
</script>
</div>
</body>
</html>
You have syntax errors in your JQuery code. The code should read:
$('document').ready(function() {
$("#shMenu").menu({
position: {
my: "center top",
at: "center bottom"
}
});
});
See working example: https://jsfiddle.net/Twisty/3z80bLed/

Categories