What is the best way to utilize window.find for adjusting CSS styles?

Incorporating both AJAX and PHP technologies, I have placed specific text data within a span element located at the bottom of my webpage. Now, my objective is to search this text for a given string. The page consists of multiple checkboxes, with each checkbox corresponding to a particular value that needs to be searched.

Objective: Employing a loop mechanism, iterate through all the checkboxes present on the page. Search the entire page for each checkbox's value (ideally within the text contained in the span informed by AJAX). If a match is found, modify the CSS style color of that particular checkbox.

The current state of my code involves a form containing checkboxes where they are named "comment" and possess unique IDs:

<input type="checkbox" name="comment" id="hjl1" value="the comment." 
 onclick="createOrder()"><label for="hjl1" onclick="createOrder()" 
 title="comment"> textual representation for this checkbox </label>

Upon activation, using JavaScript, I traverse through every checkbox within the form.

var comment=document.forms[0].comment;
var str="";
var ii;
for (ii=0;ii<comment.length;ii++)
  {str=comment[ii].value;}

My next step involves integrating window.find into that loop to verify if that particular value exists on the page.

if (window.find) {
            var found = window.find (str);
            if (!found) { 
         document.getElementById("?????").style["color"] = "red";
           }
        }

The concept revolves around checking for the presence of "the comment." value on the page when its corresponding checkbox is activated. Upon discovery, the checkbox label will display the CSS style color as red.

I aim to consolidate these concepts, yet numerous obstacles hinder progress. How can I access elements by their IDs within this loop? Is it feasible for window.find to scan the text generated by PHP in my span?

Would it prove more efficient to abstain from utilizing window.find entirely?

var source = document.getElementsByTagName('html')[0].innerHTML;
var found = source.search("searchString");

This process bewilders me as I am relatively inexperienced. Your patience and time spent reading thus far are sincerely appreciated.

Answer ā„–1

Initially, I made a mistake and wrote code to highlight text within the page.

Sure, using window.find is suitable for this purpose since you only need to determine if the value exists or not. However, its behavior may be a bit strange (scrolling to the bottom) when used in frames.

I also included a function for your onClick, although I'm uncertain if this is desired. When clicked, it will change the color of the label if the text is found.

Here's a brief example:

function checkThis(ele) {
  var str = ele.value;
  if (window.find) {
    var found = window.find(str);
    if (found) {
      var id = ele.getAttribute('id');
      var lbl = document.querySelectorAll('label[for="' + id + '"]');
      if (lbl) lbl[0].style.color = "red";
    }
  }
}

window.onload = function() {
  var comment = document.form1.getElementsByTagName('input');
  for (var x = 0; x < comment.length; x++) {
    if (comment[x].type == 'checkbox') {
      var str = comment[x].value;
      if (window.find) {
        var found = window.find(str);
        if (found) {
          var id = comment[x].getAttribute('id');
          var lbl = document.querySelectorAll('label[for="' + id + '"]');
          if (lbl) lbl[0].style.color = "red";
        }
      }
    }
  }
}

first comment.
other comment.
some comment.
the comment.
whatever comment.
not this comment.

Answer ā„–2

Here is a sample function code to try out:

function loopy() {  
   var comment=document.forms[0].comment;
   var txt="";
   var ii;
   for (ii=0;ii<comment.length;ii++) {
    if (comment[ii].checked) {
        str=comment[ii].value;
        id = comment[ii].id;

        nextLabelId = comment[ii].nextSibling.id;


        if (window.find) {        
            var found = window.find (str);
            if (found == true) {
                document.getElementById(nextLabelId).className = 'selected';                
           } 
        } else {
            alert('not supported');
        }
    }
  }
}

If you want to retrieve the checkbox id, simply include id = comment[ii].id in your loop.

To change the color, utilize class names and CSS styling. For example, to change the label after the checkbox to red, find the label's id using nextSiblings and apply the .selected class name. Remember to remove the coloring if the box is unchecked.

The use of find() may not be supported by all browsers and may have limitations when searching content injected via AJAX. Testing is recommended in such cases.

Migrating this code to jQuery might offer easier functionality for some features.

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 causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

Load the flexslider once the fancybox container is opened

In my experience, I have found flexslider and fancybox to be very useful plugins. Individually, they work perfectly fine on a website that I am currently working on. However, when I tried placing a flexslider gallery inside a fancybox div, I encountered a ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

How can I ensure my game or website fits perfectly on the screen without any need

I have recently developed a fun Erase-A-Man game that is optimized for mobile devices. However, I am facing an issue where users need to scroll to view all the letters on their screens. My goal is to make the game fit perfectly on all phone screen sizes so ...

What is the best way to incorporate (+/-) buttons to increase or decrease numbers in this code snippet?

Hey everyone, I hope you're all doing well! I need some assistance in transforming this quantity picker from a dropdown to have buttons like the one shown here with plus and minus symbols: https://i.stack.imgur.com/O0uUa.png I would like to impleme ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

Can data be passed from PHP to AJAX and back again through an AJAX to PHP request?

I recently encountered a scenario where I needed to retrieve data from a SQL database using an AJAX request in PHP. However, the challenge was finding a way to send this information back to AJAX in variables rather than simply displaying it on the screen ...

Conceal a list of items within a div that has a particular class

This is a sample of my HTML code: <div class="row"> <div class="col-md-12"> <div class="scrollbox list"> <ul class="list-unstyled"> <li id="articulate.flute">articulate flut ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

The majority of my next.js website's content being indexed by Google consists of JSON and Javascript files

Iā€™m facing an issue with Google indexing on Next.js (utilizing SSR). The challenge lies in ensuring that .HTML files are effectively indexed for SEO purposes. However, it seems that Googlebot predominantly indexes JSON and JavaScript files. To illustra ...

Activating Bootstrap modal when a navigation link is clicked

Just started a site for a client and new to Bootstrap. I've got the layout down - full-width page with "Top Nav" within the nav bar, looking to create a modal effect drop-down. When clicking on "About", it should trigger the .modal function. However, ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

Tips for deleting a button from a DataTable file upload feature

I currently have Datatable set up to upload images using the code snippet below: { label: "Images:", name: "files[].id", type: "uploadMany", display: function ( fileId, counter ) { re ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Error: The value is null and cannot be read

My external application is set up within a const called setupRemote, where it starts with the appConfig in the variable allowAppInstance. export const setupRemote = () => { if (isRemoteAvailable) { try { ... const allowAppInstance = S ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

Passing an array from JavaScript to PHP and then storing it as a .json file

Query I am trying to pass an array to PHP and save it in a data.json file. However, the data.json file is being created but showing Null as output. I have spent about 2 hours on this code, checked numerous solutions on SO, but nothing seems to work. As I ...