Javascript hiding my selected div - javascript

I have an option to select which engine package for a product on one of my e-commerce listing/product pages. Link: https://www.inflatableboats.net/avon-seasport-inflatable-boat-seasport-470-neo-2017-with-yamaha-four-stroke/.
I have a small script that changes the product description according to which engine is selected above. The problem I am running into is that I have added several other options and now it is hiding my description when the other options are selected. Here is my script as it sits on my website:
$(function() {
"use strict";
$(".specs div:gt(0)").hide();
$(".form-field-control input").click(function() {
var clicked = $(".form-field-control input").index(this);
var descriptionToShow = $(".specs div:eq(" + clicked + ")");
descriptionToShow.show();
$(".specs div").not(descriptionToShow).hide();
});
});
Now, I see part of the issue and have added an additional selector and that created a new problem.
I swapped:
var clicked = $(".form-field-control input").index(this);
to be:
var clicked = $(".form-field-radio > .form-field-control input").index(this);
This changed my problem from hiding my div to not switching back from the first div to the second. Any help is greatly appreciated, as I am not a JS expert by any means.
Here is the HTML for the engine option and the next option below it:
<div class="form-field form-field-options form-field-radio form-required" data-product-attribute="set-radio">
<div class="form-field-title product-option-title">
Engine Choice
<span class="required-text">(required)</span>
</div>
<div class="form-field-control">
<label class="form-label" data-product-attribute-value="143">
<input class="form-input form-radio" id="attribute-143" name="attribute[705]" value="143" checked="" required="" aria-required="" type="radio">
<span class="form-label-text">Yamaha F70LA Four Stroke</span>
</label>
<label class="form-label" data-product-attribute-value="144">
<input class="form-input form-radio" id="attribute-144" name="attribute[705]" value="144" required="" aria-required="" type="radio">
<span class="form-label-text">Yamaha F90LB Four Stroke</span>
</label>
</div>
</div>
<div class="form-field form-field-options form-field-checkbox form-required" data-product-attribute="input-checkbox">
<div class="form-field-title">
Pre Delivery Inspection
<span class="required-text">(required)</span>
</div>
<div class="form-field-control">
<label class="form-label ">
<input class="form-input form-checkbox" id="attribute-706" name="attribute[706]" value="116" required="" aria-required="true" type="checkbox">
<span class="form-label-text">$600 - Standard Fee requested by manufacturers, performed on new vessels, for preparing & testing the vessel on & off the water for turn-key delivery. Validates warranties. REQUIRED FEE</span>
</label>
</div>
</div>
And here is the product description html:
<div class="specs">
<p>The largest of the Zodiac Avon Seasport Deluxe inflatables, the 470 is the big boy. We rig these with Yamaha F90’s or F70's, which sound like race car engines when revved. The 470 has the deep “V” and the stern seat is moved forward a bit to support the motor and assist with planing. This boat can be expected to reach 40-45 mph on the top end, depending on conditions. The boat has a large fuel tank of 22.5 gallons, giving you a full day of play. The 470 also has many options available from the factory like a fresh water shower and picnic table, as well as synthetic teak decking and a bathing ladder.</p>
<div id="Description1">
<br />
<h3 class="specstitle">Boat Specifications</h3>
<ul class="specdetails">
<li>LOA: 15'5"</li>
<li>Beam: 6'9"</li>
<li>Weight: 910 lbs (Boat Only)</li>
<li>Capacity: 9 persons or 2083 lbs</li>
<li>Max Motor: 90 hp Long</li>
<li>Rec Motor: 70 hp Long</li>
<li>Tube Diameter: 20"</li>
<li>Air Chambers: 5</li>
<li>Fuel Tank: 22.5 gals</li>
<li>Fabric Type: Hypalon</li>
<li>Factory Warranty: 5 years</li>
</ul>
<br />
<h3 class="specstitle">Standard Features</h3>
<p>V-shaped fiberglass hull with built-in flaps, Anchor locker with upholstered seat, Rear locker with gas strut, 1 bow D-ring, 2 stern rings, Stainless steel bow rail, Rear boarding steps, Steering wheel + steering system + cable + glove box, Built-in fuel tank + gauge + fuel/water separator, Recess for extinguisher, Double pilot/co-pilot seat with removable upholstered seat, Passenger seats with removable upholstered cushion, 4 stainless steel mooring cleats, 3 lifting points, Courtesy light, Navigation lights, Battery switch + box, Automatic bilge pump, 2 paddles, foot pump, pressure gauge, repair kit, owner's manual</p>
<br />
<h3 class="specstitle">Motor Specifications</h3>
<ul class="specdetails">
<li>Engine Type: Yamaha F70LA 4-stroke</li>
<li>Horsepower: 70 hp</li>
<li>Cylinders: 4 cyl</li>
<li>Shaft Length: 20"</li>
<li>Steering: Remote mech</li>
<li>Starter: Electric</li>
<li>Weight: 253 lbs</li>
<li>Full Throttle Range: 5300 - 6300 rpm</li>
<li>Displacement: 996cc</li>
<li>Induction System: DOHC EFI</li>
<li>Warranty: 3 years</li>
</ul>
<br />
<h3 class="specstitle">Standard Features</h3>
<p>Electric start, remote mech steering, power trim & tilt, aluminum propeller, easy flush system</p>
<br />
<h3 class="specstitle">Standard Rigging</h3>
<p>Flush mounted remote control with harness and separate keyswitch, Command Link round tach and speedo, water/fuel separator, mechanical control cables</p>
</div>
<div id="Description2">
<br />
<h3 class="specstitle">Boat Specifications</h3>
<ul class="specdetails">
<li>LOA: 15'5"</li>
<li>Beam: 6'9"</li>
<li>Weight: 910 lbs (Boat Only)</li>
<li>Capacity: 9 persons or 2083 lbs</li>
<li>Max Motor: 90 hp Long</li>
<li>Rec Motor: 70 hp Long</li>
<li>Tube Diameter: 20"</li>
<li>Air Chambers: 5</li>
<li>Fuel Tank: 22.5 gals</li>
<li>Fabric Type: Hypalon</li>
<li>Factory Warranty: 5 years</li>
</ul>
<br />
<h3 class="specstitle">Standard Features</h3>
<p>V-shaped fiberglass hull with built-in flaps, Anchor locker with upholstered seat, Rear locker with gas strut, 1 bow D-ring, 2 stern rings, Stainless steel bow rail, Rear boarding steps, Steering wheel + steering system + cable + glove box, Built-in fuel tank + gauge + fuel/water separator, Recess for extinguisher, Double pilot/co-pilot seat with removable upholstered seat, Passenger seats with removable upholstered cushion, 4 stainless steel mooring cleats, 3 lifting points, Courtesy light, Navigation lights, Battery switch + box, Automatic bilge pump, 2 paddles, foot pump, pressure gauge, repair kit, owner's manual</p>
<br />
<h3 class="specstitle">Motor Specifications</h3>
<ul class="specdetails">
<li>Engine Type: Yamaha F90LB 4-stroke</li>
<li>Horsepower: 90 hp</li>
<li>Cylinders: 4 cyl</li>
<li>Shaft Length: 20"</li>
<li>Steering: Remote mech</li>
<li>Starter: Electric</li>
<li>Weight: 353 lbs</li>
<li>Full Throttle Range: 5000 - 6000 rpm</li>
<li>Displacement: 1832cc</li>
<li>Induction System: DOHC EFI</li>
<li>Warranty: 3 years</li>
</ul>
<br />
<h3 class="specstitle">Standard Features</h3>
<p>Electric start, remote mech steering, power trim & tilt, aluminum propeller, easy flush system</p>
<br />
<h3 class="specstitle">Standard Rigging</h3>
<p>Flush mounted remote control with harness and separate keyswitch, Command Link round tach and speedo, water/fuel separator, mechanical control cables</p>
</div>
</div>

I believe I have solved my own riddle. I changed my script to this and it is working. Probably only as long as I don't use radio buttons for anything else on the page.
$(function() {
"use strict";
$(".specs div:gt(0)").hide();
$(".form-radio").click(function() {
var clicked = $(".form-radio").index(this);
var descriptionToShow = $(".specs div:eq(" + clicked + ")");
descriptionToShow.show();
$(".specs div").not(descriptionToShow).hide();
});
});

Related

I want to keep the first toggle opened whenever the page opens. How can this be done?

I have tried to keep the first toggle open.
The first one should automatically be opened without clicking on the + symbol.
I tried implementing this by changing the code in javascript function.
I had changed the code to .first().show()
!function(a){"use strict";a(".pafa-accordion-a").first().show()
The above method opens all the toggle on page loading
This didn't work. Can someone guide me how to go about this?
Please find the inbuilt or existing code below:
! function(a) {
"use strict";
a(".pafa-accordion-a").hide(), a(".pafa-accordion-q").click(function() {
var b = a(this).hasClass("pafa-accordion-open"),
c = a(".pressapps_faq_accordion").find("i." + icons.faq_open);
a(".pafa-accordion-q").removeClass("pafa-accordion-open"), a(".pafa-accordion-a").slideUp(), c.removeClass(icons.faq_open).addClass(icons.faq_close), b ? (a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideUp(), a(this).removeClass("pafa-accordion-open")) : (a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideDown(), a(this).addClass("pafa-accordion-open"), a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))
})
}(jQuery),
function(a) {
"use strict";
jQuery(".pafa-list-cat a, .pafa-list-q a, .pafa-back-top").each(function() {
var b = "";
jQuery(this).click(function() {
var c = jQuery(this).attr("href"),
d = a(this).parents(".pressapps_faq_list").find(c).offset();
return b = d.top, jQuery("html,body").animate({
scrollTop: b - 30
}, 500), !1
})
})
}(jQuery),
function(a) {
"use strict";
a(".pafa-block-a").hide(), a(".pafa-block").click(function() {
var b = a(this).hasClass("pafa-block-open"),
c = a(".pressapps_faq_block").find("i." + icons.faq_open);
a(".pafa-block").removeClass("pafa-block-open"), c.removeClass(icons.faq_open).addClass(icons.faq_close), a(".pafa-block-a").slideUp(), b ? (a(this).find(".pafa-block-a").first().slideUp(), a(this).removeClass("pafa-block-open")) : (a(this).find(".pafa-block-a").first().slideDown(), a(this).addClass("pafa-block-open"), a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))
})
}(jQuery);
I had modified it with :
! function(a) {
"use strict";
a(".pafa-accordion-a").first().show(), a(".pafa-accordion-q").click(function() {
var b = a(this).hasClass("pafa-accordion-open"),
c = a(".pressapps_faq_accordion").find("i." + icons.faq_open);
a(".pafa-accordion-q").removeClass("pafa-accordion-open"), a(".pafa-accordion-a").slideUp(), c.removeClass(icons.faq_open).addClass(icons.faq_close), b ? (a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideUp(), a(this).removeClass("pafa-accordion-open")) : (a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideDown(), a(this).addClass("pafa-accordion-open"), a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))
})
}(jQuery),
function(a) {
"use strict";
jQuery(".pafa-list-cat a, .pafa-list-q a, .pafa-back-top").each(function() {
var b = "";
jQuery(this).click(function() {
var c = jQuery(this).attr("href"),
d = a(this).parents(".pressapps_faq_list").find(c).offset();
return b = d.top, jQuery("html,body").animate({
scrollTop: b - 30
}, 500), !1
})
})
}(jQuery),
function(a) {
"use strict";
a(".pafa-block-a").hide(), a(".pafa-block").click(function() {
var b = a(this).hasClass("pafa-block-open"),
c = a(".pressapps_faq_block").find("i." + icons.faq_open);
a(".pafa-block").removeClass("pafa-block-open"), c.removeClass(icons.faq_open).addClass(icons.faq_close), a(".pafa-block-a").slideUp(), b ? (a(this).find(".pafa-block-a").first().slideUp(), a(this).removeClass("pafa-block-open")) : (a(this).find(".pafa-block-a").first().slideDown(), a(this).addClass("pafa-block-open"), a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))
})
}(jQuery);
HTML Code
!function(a){"use strict";a(".pafa-accordion-a").hide(),a(".pafa-accordion-q").click(function(){var b=a(this).hasClass("pafa-accordion-open"),c=a(".pressapps_faq_accordion").find("i."+icons.faq_open);a(".pafa-accordion-q").removeClass("pafa-accordion-open"),a(".pafa-accordion-a").slideUp(),c.removeClass(icons.faq_open).addClass(icons.faq_close),b?(a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideUp(),a(this).removeClass("pafa-accordion-open")):(a(this).parents(".pafa-accordion").first().find(".pafa-accordion-a").slideDown(),a(this).addClass("pafa-accordion-open"),a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))})}(jQuery),function(a){"use strict";jQuery(".pafa-list-cat a, .pafa-list-q a, .pafa-back-top").each(function(){var b="";jQuery(this).click(function(){var c=jQuery(this).attr("href"),d=a(this).parents(".pressapps_faq_list").find(c).offset();return b=d.top,jQuery("html,body").animate({scrollTop:b-30},500),!1})})}(jQuery),function(a){"use strict";a(".pafa-block-a").hide(),a(".pafa-block").click(function(){var b=a(this).hasClass("pafa-block-open"),c=a(".pressapps_faq_block").find("i."+icons.faq_open);a(".pafa-block").removeClass("pafa-block-open"),c.removeClass(icons.faq_open).addClass(icons.faq_close),a(".pafa-block-a").slideUp(),b?(a(this).find(".pafa-block-a").first().slideUp(),a(this).removeClass("pafa-block-open")):(a(this).find(".pafa-block-a").first().slideDown(),a(this).addClass("pafa-block-open"),a(this).find("i").removeClass(icons.faq_close).addClass(icons.faq_open))})}(jQuery);
<div class="blog opened-article"><!-- Start Post Single Article -->
<article id="post-20047" class="cmsmasters_open_post post-20047 post type-post status-publish format-standard hentry category-school-of-aviation">
<div class="cmsmasters_post_cont_info entry-meta"><div class="cmsmasters_data_author"><span class="cmsmasters_post_date"><abbr class="published" title="April 27, 2021">April 27, 2021</abbr><abbr class="dn date updated" title="May 6, 2021">May 6, 2021</abbr></span><span class="cmsmasters_post_author"><span class="fn">Adarsh</span></span></div><span class="cmsmasters_post_category">School of Aviation</span></div><header class="cmsmasters_post_header entry-header"><h2 class="cmsmasters_post_title entry-title">B.Sc Aviation</h2></header><div class="cmsmasters_post_content entry-content">
<!-- Accordion Template -->
<div class="pressapps_faq_accordion">
<div class="pafa-accordion pafa-icon">
<h3 class="pafa-accordion-q"><span style="background-color:#ef3737; border-radius: 0px; ?>;"><i class="si-add-2" style="color: #ffffff"></i></span>Course Outcomes</h3>
<div class="pafa-accordion-a" style="display: none;">
<b>PROGRAM EDUCATIONAL OBJECTIVES (PEO)</b><br><br>
<span style="font-weight: 400;"><strong>PEO1:</strong> To help students to achieve deep knowledge of aviation stream we also aim to find, devolope and streamline the student’s interest in aviation and different aviation related field. </span><br><br>
<span style="font-weight: 400;"><strong>PEO2:</strong> To develope skill to identify problem that may be hazardous to the safe operations of an aircraft in the quickest and safest possible manner and solving the problem within time constraint.</span><br><br>
<span style="font-weight: 400;"><strong>PEO3:</strong> To prepare a well trained and knowledgeable aviation personnel to cope up with ever devoloping aviation industry by frequently updating syllabus in accordance to the latest update in aviation field.</span><br><br>
<span style="font-weight: 400;"><strong>PEO4:</strong> To help students to work as a team to prevent, find or solve a situation together and encourages multi crew coordination (MCC) for efficient working with minimum error.</span><br><br>
<span style="font-weight: 400;"><strong>PEO5:</strong> Encourage and train students to be well groomed and prepare them to appear on radio telephony exam conducted by Ministry of communication, Govt of India to increase their scope of job opportunity</span><br><br>
<b>PROGRAM OUTCOME (PO)</b><br><br>
<span style="font-weight: 400;"><strong>PO1:</strong> Understand the role and responsibility of aviation personnel, having leadership quality to have a streamlined operation for the benifit of company. </span><br><br>
<span style="font-weight: 400;"><strong>PO2:</strong> Gain knowledge about safe operation of aircraft and finding the possibility which hinders the safety of aircraft operation. </span><br><br>
<span style="font-weight: 400;"><strong>PO3:</strong> Understand the flow and functions of various teams, working in an airport for smooth operation of aircraft and choosing the department of his own personal interest.</span><br><br>
<span style="font-weight: 400;"><strong>PO4:</strong> Understand the restrictions, rules, the Do’s and Dont’s within an aerodrome area, to help the security executives to create a more safe air operations.</span><br><br>
<span style="font-weight: 400;"><strong>PO5:</strong> Knows to work as a team in different sitiuation and handling the situation as a team and knows the value of multi crew coordination (MCC).</span><br><br>
<span style="font-weight: 400;"><strong>PO6:</strong> Have a clear idea about different documents and manual which are used by different department in aviation, the procedure to use and the process of updating it</span><br><br>
<span style="font-weight: 400;"><strong>PO7:</strong> Have basic knowledge about aero medical, understands resource management, work load, stress management. Can judge various weather conditions, weather report, forecast and its effect.</span><br><br>
<b>PROGRAMME SPECIFIC OUTCOME (PSO)</b><br><br>
<span style="font-weight: 400;"><strong>PSO1:</strong> Be well familiar with various department of aviation stream and have deep knowledge about their responsibilities and duties.</span><br><br>
<span style="font-weight: 400;"><strong>PSO2:</strong> Be competent in the field of aviation meteorology, air regulations, air navigations, aircraft technical, radio telephony</span><br><br>
<span style="font-weight: 400;"><strong>PSO3:</strong> To adopt themself with the new technology which is devoloped to improve the safety, efficiency and streamlined flow of air traffic. </span><br><br>
<span style="font-weight: 400;"><strong>PSO4:</strong> Well known about the importance of muti crew coordinaton (MCC), working and handling the situation as a team.</span><br><br>
<span style="font-weight: 400;"><strong>PSO5:</strong> Will be a professional aviation personnal who knows their roles and responsibilities in their concerned field and ability to grow in their field for the benifit of themself and aviation industry.</span><br><br> </div>
</div>
<div class="pafa-accordion pafa-icon">
<h3 class="pafa-accordion-q"><span style="background-color:#ef3737; border-radius: 0px; ?>;"><i class="si-add-2" style="color: #ffffff"></i></span>Eligibility Criteria</h3>
<div class="pafa-accordion-a" style="display: none;">
<p><strong>Click here to check your Eligibility</strong></p>
</div>
</div>
<div class="pafa-accordion pafa-icon">
<h3 class="pafa-accordion-q"><span style="background-color:#ef3737; border-radius: 0px; ?>;"><i class="si-add-2" style="color: #ffffff"></i></span>Fee Structure</h3>
<div class="pafa-accordion-a" style="display: none;">
<p><strong>B.Sc Aviation Fee structure</strong></p>
</div>
</div>
<div class="pafa-accordion pafa-icon">
<h3 class="pafa-accordion-q"><span style="background-color:#ef3737; border-radius: 0px; ?>;"><i class="si-add-2" style="color: #ffffff"></i></span>Subjects</h3>
<div class="pafa-accordion-a" style="display: none;">
<p><b>SEMESTER-1</b></p>
<p><b>FAMILIARIZATION OF AIRPORT</b></p>
<p><b>Course Objective: </b></p>
<p><span style="font-weight: 400;">To acquire basic understanding of the layout of an Airport; its buildings, facilities, installations and their functioning.</span></p>
<p><b>UNIT 1: Buildings & Installations </b></p>
<p><span style="font-weight: 400;">Terminals, Security, Apron, Hangar, Taxiway, Runway,Fire Station, Airport Vehicles, Fuel depot</span> <b>12</b></p>
<p><b>UNIT 2: Markings& Lightings</b></p>
<p><span style="font-weight: 400;">RWY & TWY markings, Lightings, Signboards, Declared distances, PCN, Lighting system, Aerodrome Beacon, Obstacle Lighting & Marking</span></p>
<p><b>UNIT 3: Facilities&Equipments</b></p>
<p><span style="font-weight: 400;"> Navigational facilities:VOR, NDB, DME; Surveillance equipments:Primary Radar, SSR, Surface Movement Radar, ADS; GPS, VHF antennae, ILS</span></p>
<p><b>UNIT 4: Air Traffic Control</b></p>
<p><span style="font-weight: 400;">ATC Units, Concept of FIR, Role of FIC, Roles of Tower & SMC Controllers, Flight Plan, Flight Dispatch, ATC briefing</span></p>
<p><b>UNIT 5: Important Organizations</b></p>
<p><span style="font-weight: 400;">Ministry of Civil Aviation, ICAO, DGCA, AAI & its wings, BCAS, CISF, MLU </span></p>
<p><b>TOTAL 60Hrs</b></p>
<p><strong>Reference:</strong></p>
<ul>
<li aria-level="1"><b><span style="font-weight: 400;">ICAO Annex 14 Volume 1 Aerodrome Design and Operations</span></b></li>
</ul>
<ul>
<li aria-level="1"><span style="font-weight: 400;">Civil Aviation Requirements Section-4, Aerodrome Standards & Air Traffic Services.</span></li>
</ul>
<p><strong>VIEW ALL</strong></p>
</div>
</div>
</div>
</div><footer class="cmsmasters_post_footer entry-meta"><div class="cmsmasters_post_meta_info entry-meta"><span class="cmsmasters_likes cmsmasters_post_likes"><span>0 </span></span></div></footer></article>
<!-- Finish Post Single Article -->
<aside class="post_nav"><span class="dn"></span></aside></div>
I see you're loading jQuery on that site. What about using it to hit the first accordion item when loading?
Something like:
jQuery( document ).ready(function() {
jQuery(".pressapps_faq_accordion div:nth-child(1) span").click();
});
Ideally you'd edit the html so you have an id to grab onto and so you can more easily use this code elsewhere on the site, but I think it'll work anyway like this.

Word search with span element count

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.

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>

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