Is there a way to have the span update even if the input stays the same? Currently, it only changes when the input is different

Retrieve results of 3 lines (Ps) by entering a word in the text area and clicking search.

If the word is found after clicking the button, a span will be displayed with the count of occurrences as well as the highlighted P(s) where it was found.

If the word is not found after clicking the button, a span will display that the word was not found.

IT WORKS!

The issue lies in updating the count in the span if the same word is searched for a second time

For instance, searching 'Suns' the first time retrieves a count of 2 because it was found twice. If searched again, the count remains the same, while I want it to update to 4. A new word search should display only the new word's result without affecting the first word count.


          but1 = document.querySelector("#searchbutton");
          but1.addEventListener('click', searchClick);
          
          function searchClick() {
            var searchPhrase = document.querySelector("#searchtext").value;
            var main = document.querySelector("#main");
            var mainParas = main.querySelectorAll(" p ");
            
            for (var i = 0; i < mainParas.length; i++) { 
              if (mainParas[i].textContent.indexOf(searchPhrase) >= 0) { 
                mainParas[i].className = "highlighted"; } 
              else { 
                mainParas[i].className = null; 
              }
            }
          }

          function count_search() {
            var allPs = "";
            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 => allPs += el.innerText);
  
            var regex = new RegExp(searchPhrase, "gi");
            var times = allPs.match(regex);
            document.getElementById("output").innerHTML = times ? `How many times I searched for the word ${searchPhrase}: ${times.length}` : "No matches found";
          }
        
      

          .highlighted {
            background-color: yellow;
            border: 1px dashed #666600;
            font-weight: bold;
          }
  
          #output{
            position:relative; 
            top:50px;
          }
        
      

          <html>
          <head>
            <script src="dom_2_alt.js" type="text/javascript" defer></script>
            <link href="outstyle.css" type="text/css" rel="stylesheet" />
          </head>
                      
          <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>
                        
          </html>
        
      

Answer №1

It seems like you are looking to maintain a running count of search results, with the expected outcome as follows:

  • "Suns" : 2
  • "Suns", "Suns": 4
  • "Arizona": 1
  • "Suns", "Arizona": 3

To reset the count, a page reload is necessary.

To achieve this, there are two potential approaches that come to mind. The first involves creating a global variable named times within your function count_search()

For example:

let times = 0;
function count_search() {
...

In this scenario, you would need to modify your existing var times = allPs.match(regex); line to

times = times + allPs.match(regex).length;

The second option entails incorporating a new <span></span> element for displaying the result. Each time your program runs, you can extract and convert the content of the span into a number (as it will be in string format), add the new times value to it, and then update the span's content accordingly.

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 method for restricting the visibility of an animation to specific regions within an SVG?

I am seeking assistance with adding a "shine" animation to my SVG. I want the animation to only appear within specific parts of the SVG, but I'm uncertain about how to achieve this. Below is what I have accomplished so far. The aim is for the white ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

How can I create a responsive input group with automatic width using Bootstrap 3.1?

I am having trouble with the layout of my two floating divs. The first div contains buttons and the second div contains an input-group. However, the input-group is moving down a line instead of utilizing the available space. Here is a link for reference: ...

What is the best way to repurpose the vuex module for multiple components?

Currently, I am tackling the pagination aspect of a project that involves handling a large amount of data. My initial instinct was to store this data within Vuex. However, I ended up implementing all the logic in the Vuex store module. Now, my goal is to f ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Ensure proper tagging by adding a closing tag to the HtmlElement in HtmlUnit

I am looking to convert an Html page to pdf, but the HtmlPage contains many unclosed tags like: < hr > < br > Because of these unclosed tags, I am unable to create a Pdf. Is there a way to close these tags using HtmlUnit in Java? What I need ...

Is it feasible to develop an asynchronous function in Node.js that executes concurrently?

My objective is to simultaneously execute the longRunnigTask and quickTask functions: function longRunnigTask() { return new Promise((resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i+ ...

Navigation website with a twist

My design features a main navigation that is rotated 90 degrees, while the sub-menu remains horizontally aligned. <div id="nav"> <ul> <li><a href="#">Woonaccessoires</a></li> ...

Displaying numbers as characters in AngularJS: Use $index variable

Within my ng-repeat, I have two <li> tags repeating a specific number of times. The $index is being used to determine the position of each <li>. You can view a sample on this fiddle: http://jsfiddle.net/sh0ber/cHQLH However, I would like one ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

Issues with CSS selectors in Internet Explorer causing problems with Selenium Webdriver C#

When automating a website with Selenium C#, I encountered a NoSuchElementException when trying to click an element using a CSS selector. However, the issue was resolved when using xpath instead. Can someone shed light on why this discrepancy between CSS an ...

Retrieving various sets of JSON objects arrays

I have successfully stored an array of JSON objects in the database using the following code: function send_custom_markers() { var reponse = confirm("Send markers to selected contacts?"); if (reponse === true) { var json_markers = new ...

Set the datepicker with the window positioned to the right side

In my current project, I am utilizing Angular 13, Bootstrap 5, and ngx-bootstrap-fix-datepicker version 5. "bootstrap": "^5.1.3", "ngx-bootstrap": "^8.0.0", "ngx-bootstrap-fix-datepicker": "^5.6.8" ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...

Evaluating manually bootstrapped AngularJS applications

I've encountered an issue while testing an AngularJS application (using Karma and Jasmine) where I manually bootstrap the application in the code after some HTTP AJAX requests. angular.module("app", []); angular.element(document).ready(function() { ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Developing a user authentication system with TowerJS

As a front-end designer/developer with limited MVC experience, I am looking to create a login form using TowerJS. Following the documentation, my app includes a model named "User": class App.User extends Tower.Model @field "email", type: "String" @fie ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...