Skip to content Skip to sidebar Skip to footer

Targeting Specific Text Entered Into Form Input Field And Add Styles To It?

How can I style the 2nd word entered into a form input text field? Not in the field itself where they are entering the text, but once the person entering the text hits the 'enter'

Solution 1:

Given a string of words, I think the easiest way to style individual words is to .split() the input string into an array of individual words and then update whichever one(s) you wanted to based on their position in the array, before .join()ing back together into a string of HTML. In that way it is easy enough to wrap an individual word in a span element with a specific class, and then style that class however you like.

"The text is entered by a site administrator and gets output to the front of the site on a page. There must be a way this can be targeted and styled."

Yes. Select the element in question with jQuery and then apply the above technique to it. Perhaps a little something like this:

$(".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; }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Some text.</p><pclass="styleMe">These are some words to be styled.</p><p>Some other text.</p>

Note: if there is a possibility the input format may vary in length then obviously you should test that, so that, e.g., you're not trying to update the second word in a string that only has one word in it.

Post a Comment for "Targeting Specific Text Entered Into Form Input Field And Add Styles To It?"