Utilizing arrays to dynamically alter the text color of specific words in an input field

Currently, I am in the process of working on a JSFiddle and find myself a bit puzzled by a certain aspect. Within my project, I have an input box named myTextField which contains a random paragraph. Additionally, there is a button that triggers my change function. Presently, when the button is clicked, the text displayed in the box is simply shown below it. However, I am seeking to enhance this functionality by changing the color of specific words from an array, let's say to blue. Any guidance on this matter would be greatly appreciated, as I am relatively new to HTML/CSS/JS and may not have all the correct terminology at my disposal.

MyHTML

 <input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well-fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters."/>
    <input type="submit" id="byBtn" value="Change" onclick="change()"/>
    <p id="title"></p>

Javascript

change = function(){
var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all",
"its", "no", "this", "any", "those", "both", "least", "our",
"what", "each", "less", "several", "which", "either", "many", "some",
"whose", "enough", "more", "such", "your"];
//if a value from array matches a value from myTextField
    if (matches===document.getElementById('myTextField'))
    {
            //change color of said words
    }
       var myNewTitle = document.getElementById('myTextField').value;
       var title = document.getElementById('title');
       title.innerHTML = myNewTitle;
    }

https://jsfiddle.net/hnfe3Lgk/

Answer №1

If you're looking for a solution, consider the following approach:

transform = function() {
  var keywords = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all",
    "its", "no", "this", "any", "those", "both", "least", "our",
    "what", "each", "less", "several", "which", "either", "many", "some",
    "whose", "enough", "more", "such", "your"
  ];

  // retrieve the current value of the "myTextField" element
  var myTextFieldValue = document.getElementById('myTextField').value;

  // split the string at every space character to form an array of words
  var myTextFieldWords = myTextFieldValue.split(' ');

  // for each word, check if it is present in the "keywords" array
  // if yes, wrap it in a <span class="match"> tag
  var formattedWords = myTextFieldWords.map(function(word) {
    if (keywords.indexOf(word) !== -1) {
      return '<span class="match">' + word + '</span>';
    } else {
      return word;
    }
  });

  // formattedWords now represents the words with tags
  // join all the words in the formattedWords array with a space
  // set it as the innerHTML of the #title element
  document.getElementById('title').innerHTML = formattedWords.join(' ');
}
.match {
  color: blue;
}
<input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters." />
<input type="submit" id="byBtn" value="Transform" onclick="transform()" />
<p id="title"></p>

Answer №2

Here's a possible solution you could try out

Suppose you're looking to alter the text displayed when the field loses focus

var input = document.getElementById("my-input");
var par = document.getElementById("par");

var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all",
"its", "no", "this", "any", "those", "both", "least", "our",
"what", "each", "less", "several", "which", "either", "many", "some",
"whose", "enough", "more", "such", "your"];

input.addEventListener("blur", function() {
    var inputValue = input.value;
    par.innerHTML = "";
    inputValue.split(' ').forEach(function(word) {
        if (matches.indexOf(word) > -1) {
          par.innerHTML += "<span class='colored'>" + word + " " + "</span>";
        }
        else {
            par.innerHTML += word + " ";
        }
    });
});
.colored {
  color: blue;
}
<textarea id="my-input"></textarea>

<p id="par"></p>

Answer №3

My solution utilizes a single regular expression and avoids the need for any looping. The key component is the regex pattern

/(^|\W)(every|most|...|your)(?=\W|$)/g
used for replacement.

my_change = function(){

  var myNewTitle = document.getElementById('myTextField').value;
  if( myNewTitle.length==0 ){
    alert('Write Some real Text please.');
    return;
  }

  var title = document.getElementById('title');

  var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all", "its", "no", "this", "any", "those", "both", "least", "our", "what", "each", "less", "several", "which", "either", "many", "some", "whose", "enough", "more", "such", "your"];

  var r = new RegExp('(^|\\W)('+matches.join('|')+')(?=\\W|$)', 'g');
  title.innerHTML = myNewTitle.replace(r, '$1<span>$2</span>');

};

my_remove = function(){
  document.getElementById('title').innerHTML = "";
}
span { color: blue; }
<input type="text" id="myTextField" value ="It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife. However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters."/>

<input type="submit" id="byBtn" value="Change" onclick="my_change()"/>
<input type="button" id="refresh" value="Reset" onclick="my_remove()"/>

<p id="title"></p>

Answer №4

To find a solution, you can search the word array and compare it to the value. The original code checked whether the element was an array.

(function() {
  'use strict';

  function change() {
    var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all", "its", "no", "this", "any", "those", "both", "least", "our", "what", "each", "less", "several", "which", "either", "many", "some", "whose", "enough", "more", "such", "your"],
      myNewTitle = document.getElementById('myTextField').value,
      title = document.getElementById('title'),
      doesMatch = matches.reduce(word => myNewTitle.search(word) >= -1);

    if (doesMatch) {
      console.log('yes');
      title.style.color = 'green';
    } else {
      console.log('no match');
      title.style.color = 'red';
    }

    title.innerHTML = myNewTitle;
  }


  document.querySelector('#byBtn').addEventListener('click', change, false);
}());
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Using Arrays to change color...</title>
</head>

<body>

  <input type="text" id="myTextField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters." />
  <input type="submit" id="byBtn" value="Change" />
  <p id="title"></p>

</body>

</html>

Answer №5

To begin, you'll first want to divide your input string value into an array.

var inputString = document.getElementById('inputField').value;
inputString = inputString.split(" ");

Next, you can compare the two arrays using nested for loops that iterate based on the length of each array. Here's how you can embed a for loop within another:

var matchingWords = document.getElementById("output");
var match = 0;
for (var i = 0; i < inputString.length; i++) {
  for (var j = 0; j < matches.length; j++) {
    if (inputString[i] == matches[j]) {
      match = 1;
      matchingWords.innerHTML += "<span style='color:blue'>" + " " + inputString[i] + " " + "</span>";
    } else if ((j == matches.length - 1) && match === 0) {
      matchingWords.innerHTML += " " + inputString[i];
    } //else if
  } // for j
} // for i

Additionally, you'll need to establish a trigger that determines whether a match has been found or not.

If a match is found, set the match variable to 1 to bypass the else if condition. However, if no match is found and you reach the end of the inner loop, print the word without any special coloring.

Feel free to check out this jFiddle link I've prepared for you. I hope this explanation proves to be helpful. https://jsfiddle.net/unique/s0nc734p/78/

Below is the complete HTML code snippet:

<input type="text" id="inputField" value="his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters. " />
<br>
<input type="submit" id="changeBtn" value="Change" onclick="change()" />
<p id="output"></p>

And here is the complete JavaScript code snippet:

var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all", "its", "no", "this", "any", "those", "both", "least", "our","what", "each", "less", "several", "which", "either", "many", "some", "whose", "enough", "more", "such", "your"];

change = function() {
  var inputString = document.getElementById('inputField').value;
  inputString = inputString.split(" ");
  var matchingWords = document.getElementById("output");
  var match = 0;
  for (var i = 0; i < inputString.length; i++) {
    for (var j = 0; j < matches.length; j++) {
      if (inputString[i] == matches[j]) {
        match = 1;
        matchingWords.innerHTML += "<span style='color:blue'>" + " " + inputString[i] + " " + "</span>";
      } else if ((j == matches.length - 1) && match === 0) {
        matchingWords.innerHTML += " " + inputString[i];
      } //else if
    } // for j
    match = 0; // reset match
  } //for i
} //change

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 process of invoking Link manually in React-router?

I am working on a component that is passed a <Link/> object from react-router as a prop. When the user clicks on a 'next' button within this component, I need to manually trigger the <Link/> object. Currently, I am using refs to acce ...

Identifying the initial object with a duplicate property within an array of objects using JavaScript

In my code, I have an array structured like this: var myArray = [ {id: 1, entry_id: 1, name: 'test', email: 'email1'}, {id: 2, entry_id: 1, name: 'test', email: 'email2'}, {id: 3, entry_id: 2, name: &ap ...

Using BeautifulSoup to Retrieve JPEG from an Image Tag's Src Attribute

Struggling with scraping this webpage for personal use. I am having trouble extracting the thumbnails of each item on the page. Despite being able to see image tags containing the required .jpgs when using "inspect" to view the html DOM, I cannot find the ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

Modify text input when a different option is selected (with both options originally coming from a database)

A dropdown menu is filled with options from a database, and the chosen option is compared to a variable $comp_cntry currently on the page: <select name="country"> <option value="--" disabled>Please Select...</option> <option v ...

Tips for sending an array of data from the client to req.body in an axios request

I am facing an issue with sending user data collected from the front end via an ajax call to an axios post request in the back end. The parameters I need to pass include arrays of data, but when I check the req.body in the backend using console.log(), I no ...

KineticJs: Enhancing Rotation with Multitouch Capability

Currently, I have a click event implemented in my code that rotates my puzzle piece by 90 degrees when clicked. However, I would like to change it from a mouse click to a touch event. How can I achieve this? Thank you. piecesArray[i][j].shape.on("mous ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Using jQuery to make an element follow you as you scroll down a page inside a div

I've made some progress on my code: HTML <div id="header"></div> <div id="content"> <div class="sidebar-wrapper"></div> </div> <div class="session-wrapper"></div> <div id="footer"></div> ...

Display or conceal numerous WTForm labels

Is there a more efficient way to hide/show multiple wtform labels? Currently, I am achieving this with the following code: HTML: {{ render_field(var_1, class = "class_1") }} {{ render_field(var_2, class = "class_1") }} {{ render_field(var_3, class = " ...

Add characterizations to object utilizing cropper plugin

After obtaining image attributes from the cropper plugin, I am looking to include two additional values: var data = $img.cropper('getData'); //Object {x: 90, y: 60, width: 720, height: 480, rotate: 0…} image_identifier = $('.image_identi ...

Ways to retrieve the upcoming possible date

I'm currently working on a project using express and I need to implement a scheduling calendar. My goal is to provide users with the next available day in the format YYYY-MM-DD. Here are the rules for determining the next available day: The default ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

Adding jQuery SVG Sources to SVG Elements

Can the jQuery SVG source code be included in a standalone SVG document? Here is an example: <script type="application/javascript"> <![CDATA[ // jQuery SVG code ]]> </script> I want the SVG document to be self-contained, ...

Achieve a floating right alignment of an unordered list navigation using CSS without changing

I am currently implementing a jquery navigation system which can be found at this link: http://css-tricks.com/5582-jquery-magicline-navigation/ My goal is to have the navigation bar float to the right without changing the order of items (e.g. home, contac ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected. function showImage() { $('.img').addClass('display'); } function hideImage() { $('.img'). ...

Manipulating SVG on a UIWebview dynamically

Seeking guidance on manipulating SVG files loaded into a UIWebview. Currently, I load an SVG file into an HTML file and then into a UIWebview. Presumably, Javascript is required for this, but unsure about the exact process. Ideally, I aim to dynamically ma ...