How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output?

In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name.

For example:
If I type "903 Houston" in the input field and display it, how can I highlight or style the second word ("Houston") separately from the rest of the text (e.g., make it bold) so that it outputs as "903 Houston"? Would I need to use HTML tags to modify just the second word that's being entered into the form? How could this task be achieved?

Answer №1

When dealing with a string of words and wanting to style individual words, one effective method is to utilize the .split() function to break down the string into an array of words. Subsequently, you can modify specific words based on their position in the array and then reassemble them using the .join() function to form a cohesive HTML string. This approach allows for easy encapsulation of individual words within span elements adorned with custom classes for personalized styling.

"Text inputted by a website administrator is displayed on the frontend of the site. There must be a way to target and enhance its appearance."

A viable solution involves selecting the desired element using jQuery and implementing the aforementioned technique. A sample implementation could resemble the snippet below:

$(".styleMe").html(function(i, currentText) {
    var words = currentText.split(" ");
    words[1] = "<span class='bold'>" + words[1] + "</span>";
    words[3] = "<span class='highlight'>" + words[3] + "</span>";
    return words.join(" ");
});
.bold { font-weight: bold; }
.highlight { background-color: blue; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some text.</p>
<p class="styleMe">These are some words to be styled.</p>
<p>Some other text.</p>

It's important to note that in scenarios where the length of the input may vary, conducting thorough testing is essential to prevent errors when attempting to manipulate words that do not exist.

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

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

"Troubleshooting: Why is my AngularJS ng-click not triggering the function

My custom directive fetches a navigation block from a webservice call. I am attempting to click on a navigation link that has an "ng-click" attribute set, which should call the specified function. However, the function is not being executed. Below is my r ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

How can I output HTML code using php echo without using quotation marks?

My issue involves printing out HTML code that is not stored as a simple string, requiring me to decode it before echoing. The problem arises when I echo the decoded value and unwanted quotes appear, disrupting the output. Here's an example: <div> ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate loca ...

Is there a way to preserve the context in React when transitioning to a new page?

Currently, I am encountering a challenge within my React application involving multiple components, each utilizing its own context through the useContext hook. My goal is to uphold the context for each component even when there are changes in the URL. I a ...

Artistically connect the main navigation bar to the secondary one

I am currently working on developing a responsive website. I am following the "content first" methodology, starting with designing for the smallest mobile layout. The homepage of the site (still under construction) looks something like this: When a user c ...

Unable to access variable using GET method, however able to retrieve it using var_dump($_GET)

I am attempting to create a simple AJAX call that passes a variable and displays it in a modal. The passing of the variable is successful, however, I am unable to retrieve the variable from the GET method. When using echo var_dump($_GET);, I get: array(2 ...

Pressing a button is a way to select a specific form

I'd like to create a clickable button that can direct users to the form section on the same page. <button type="button" class="btn btn-primary btn-sm"> Go to Form Section </button> ... <form id="form1"> <div class="form-g ...

What issues are present in the Ajax script and the PHP radio input?

I'm having trouble extracting the value of a radio input in this code so I can update the database: <script type="text/javascript> function getVote() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlh ...

rearranging the positioning of links in the HTML navbar

Is there a way to prevent other links in the navbar from moving up slightly when hovering over one link and creating a line (border bottom)? ` .n24{ margin-top: 2px; padding: 14px 14px; } .n25{ margin-top: 2px; padding: 14px 14px; } . ...

Validating forms using jQuery before making an Ajax call to submit them

I'm struggling to implement form validation before submitting it via Ajax to my php script. Despite researching on stackoverflow, I haven't found a solution that fits my needs. My form consists of 3 inputs and a submit button: <input type="t ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

Ensuring the Accuracy of POST Parameters Using Express-Validator

I've been working on adding parameter validation to my Node/Express API by utilizing express-validator. However, I encountered a situation where even though I sent a POST request with a missing "name" field using the curl command curl -X POST -d "foo= ...

Collaborative Vue component: Clients need to manually import the CSS

I recently created a Vue component using TypeScript that resulted in a separate CSS file being generated after the build process. However, I noticed that when the client imports this component, the CSS file is not imported automatically and needs to be exp ...

How can I use the import statement to incorporate the 'posts.routes.js' file into my app using app?

Searching high and low for answers but coming up empty. When setting up an express app and including a file of routes, you typically encounter guidance on using the following statement: require('./app/routes/posts.routes.js')(app) As per nodejs. ...

Intermittent issues with requesting JSON data

My current project involves building a script that iterates through a list, retrieves product SKUs, and includes them in a JSONP request to retrieve an object. The script seems to be functioning as intended, but there are occasional failures. Here is an e ...

"Freezing issue with Angular big table causing web page to lock up during

Looking for a way to improve the performance of an HTML table search function that is currently running very slowly and freezing the web page upon loading and searching. The table needs to be within the HTML file itself, not pulling data from a server. Any ...