how to highlight the words which are invalid in input given by a user - html

how to highlight only the words which are invalid in input given by a user where i can make my custom invalid check function.
e.g
hello this is very good and very nice.
suppose this is the input by the user and suppose i want to highlight "very" and "this" or any other custom word.
I have tried putting html tag inside value but html does not parses inside value attribute of input tag.

Try using variable.split() in reading the input. Store it in array using loop and check for errors and highlight

You cannot simply put html tags in input. To enable "rich text" capabilities, you'll have to use the contenteditable HTML attribute, like so...
const words = [/(very)/gi, /(nice)/gi]
const highlightInput = () => {
const richInput = document.getElementById('rich-input')
let text = richInput.innerText
words.forEach(x => {
text = text.replace(x, '<span class="highlighted">$1</span>')
})
richInput.innerHTML = text
}
document.getElementById('highlight').addEventListener('click', highlightInput)
#rich-input{
border:1px solid #000;
padding: 5px;
}
.highlighted{
color:red;
text-decoration:underline;
}
<div>
<input type="button" value="Highlight!" id="highlight" />
</div>
<label>Enter your text below:</label>
<div id="rich-input" contenteditable="true">Hello this is very good and very nice</div>

Related

angular ngModel style

Is it possible to style the value in the attribute ngModel of an input tag?
Example:
<input class="input" type="text" [(ngModel)] = "myService.text">
Let's say the value of text is '28 packages', can I put 28 in bold?
So if i understand correctly you want to have it bold whenever the value is 28 ?
yes its possible you can use a ng-class with a ternary expression like this
.bold{
font-weight:600;
}
<input type="text" ng-class="myService.text == '28 ? 'bold' : '''" class="input" ng-model="myService.text" />
This is not angular-related rather a CSS related question.
You cannot style only a part of an input in HTML/CSS so you won't be able to do it in angular.
Instead, you can use an input that is hidden behind a div. The idea is that when the user clicks the div, you actually focus the input. When the user types text, you capture the content of the input and fill the div with it, eventually adding <span class"highlight"> around the number of packages.
I prepared you a stackblitz in pure CSS/JS. You can adapt it in angular if you want.
Relevant pieces of code :
HTML :
<span id="hiddenSpan">This is the hidden div. Click it and start typing</span>
<div>
<label for="in">The real input</label>
<input id="in" type="text">
</div>
JS :
const input = document.getElementById('in')
const hiddenSpan = document.getElementById('hiddenSpan')
function onInputChanged() {
let text = input.value
const regex = new RegExp('(\\d+) packages')
let result = regex.exec(text)
if(result) {
hiddenSpan.innerHTML = '<span class="highlight">'+result[1]+'</span> packages'
} else {
hiddenSpan.innerHTML = text
}
}
// Capture keystrokes.
input.addEventListener('keyup', onInputChanged)
// Focus the input when the user clicks the pink div.
hiddenSpan.addEventListener('click', function() {
input.focus()
})
CSS :
#hiddenSpan {
background-color: pink;
}
.highlight {
font-weight: bold;
background-color: greenyellow;
}
Note : the downside is that the blinking caret is not visible anymore. You can take a look at this resource if you want to simulate one.
It is not possible to style certain parts of a text <input> field in bold. However, you can use a contenteditable div instead of a text <input> field. Inside the contenteditable div you can have other HTML tags like <strong> to style certain parts of the text however you like.
I created an Angular directive called contenteditableModel (check out the StackBlitz demo here) and you can use it to perform 2-way binding on a contenteditable element like this:
<div class="input" contenteditable [(contenteditableModel)]="myService.text"></div>
The directive uses regular expressions to automatically check for numbers in the inputted text, and surrounds them in a <strong> tag to make them bold. For example, if you input "28 packages", the innerHTML of the div will be formatted like this (to make "28" bolded):
<strong>28</strong> packages
This is the code used in the directive to perform the formatting:
var inputElement = this.elementRef.nativeElement;
inputElement.innerHTML = inputElement.textContent.replace(/(\d+)/g, "<strong>$1</strong>");
this.change.emit(inputElement.textContent);
You can change the <strong> tag to something else (e.g. <span style="text-decoration: underline"> if you want the text to be underlined instead of bolded).
When performing the formatting, there is an issue where the user's text cursor position will be unexpectedly reset back to the beginning of the contenteditable div. To fix this, I used 2 functions (getOriginalCaretPosition and restoreCaretPosition) to store the user's original cursor position and then restore the position back after the text formatting is performed. These 2 functions are kind of complex and they're not entirely relevant to the OP's question so I will not go into much detail about them here. You can PM me if you want to learn more about them.

How do I duplicate 'input required' functionality without sending with the form?

I would like to have the built-in functionality of having a text input (in the middle of other text inputs) be checked and flagged (i.e. the default red marquee applied around the text box) to make sure it is populated before the user clicks the form submit button, without including that value in the form submission. Basically, I don't want to send the retyped password with the form, but it of course needs to be filled in (and will be checked client-side). Is there a "simple" way to do this?
Here is a very minimal example of what you want.
You can do this type of logic using JavaScript events like onblur, onfocus, onchange, etc.
Here is an example showing you how you can validate that a field has a value in it.
var validate = function(element) {
// element is HTMLInputElement
if (element.value == "") {
element.className = "border-red";
} else {
element.className = "";
}
}
.red {
color: red;
}
.border-red {
border: 2px solid red;
}
<form>
Required: <input type="text" name="required_field" onblur="validate(this)" />
Optional: <input type="text" name="optional" />
</form>

AngularJs - how to support a textbox with hyperlinks

I'm new to Angular but I'm trying to implement a textbox that allows users to enter in links. I only want to support links, and otherwise I want to block all html from being presented as such. I could theoretically use something other than a textarea, but my requirements are that it must be bound to a variable in my scope (right now with ng-model) and I cannot accept html tags other than '< a >'
Here is my example plnkr
In the example, I would like the second seeded item to display as a link, blue and underlined. However, the third item should display as it is currently shown (without interpreting it as html).
HTML:
<textarea maxlength="160" ng-model="val.text"></textarea>
<div class="btn" ng-click="submit()">Submit</div>
<br><br>
<div ng-repeat="item in items">
{{display(item)}}
</div>
JS:
$scope.submit = function() {
if (!$scope.val.text) return
$scope.items.push($scope.val.text);
}
$scope.display = function(txt) {
return txt;
// something here? if txt contains <a> and </a> indicate
// that we should display as html
}

Is it bad to put <span /> tags inside <option /> tags, only for string manipulation not styling?

I would like to make groups of the text content of an <option /> tag. Say I have the following: <option>8:00 (1 hour)</option>, the time pattern 8:00 can be modified, then the text in parenthesis (1 hour) can also be modified.
I was thinking of doing something like
<option>
<span>8:00</span>
<span> (1 hour)</span>
</option>
Is it bad to put <span /> tags inside <option /> tags, only for string manipulation not styling?
From the HTML 5spec:
Content model:
If the element has a label attribute and a value attribute: Nothing.
If the element has a label attribute but no value attribute: Text.
If the element has no label attribute and is not a child of a datalist element: Text that is not inter-element whitespace.
If the element has no label attribute and is a child of a datalist element: Text.
So depending on context there are two things that you can put inside an <option> — text or nothing at all — you may not put a <span> or any other element there.
From the HTML 4.01 spec:
<!ELEMENT OPTION - O (#PCDATA) -- selectable choice -->
(Even the HTML 3.2 and HTML 2 specs say: <!ELEMENT OPTION - O (#PCDATA)*>)
An option element cannot have any child elements. So yes, it is bad.
You can use a Javascript plugin to overcome this limitation. For example jQuery plugin "Select2" Select2 plugin homepage. I use it in a couple of my projects and think that it's pretty flexible and convenient.
There are a number of them, but they do quite same thing - convert traditional <select> into <div> blocks with an extra functionality.
The option element
Content model: Text
No, it’s not ok. Consider keeping the values around in your script so you can recompose them when necessary.
You're better off using an HTML replacement for your <select> if you want to do this.
As established by other people, and I have tried with <b> and other tags, <option> does not take tags within it.
What you can do, since you cannot use <span> inside an <option> tag,
You can use the index number to extract the text via
document.getElementById(selectid).options[x].text where x is the relevant index, as a variable.
Then what you do is use the " (" to split the variable into the time, and remove the last character as well which removes the ")"
Sample:
<script type="text/javascript">
function extractSelectText()
{
var text = document.getElementById("main").options[1].text
/*
var tlength = text.length
var splitno = tlength - 1
var text2 = text.slice(0, splitno)
var textArray = text2.split(" )")
var time = textArray[0]
var hours = textArray[1]
}
</script>
Changing it is much simpler:
<script type="text/javascript">
function changeSelectText()
{
/* add your code here to determine the value for the time (use variable time) */
/* add your code here to determine the value for the hour (use variable hours) */
var textvalue = time + " (" + hours + ")"
document.getElementById("main").options[1].text
}
</script>
If you use a for function you can change each value of the select replacing 1 with 2, 3 and so on, and put a set interval function to constantly update it.
One option for editing would be to use some fancy pattern matching to update the content. It will be slower and more resource intensive, and depends on how regular the format is, but doesn't require any HTML modifications. My concern, however, would be on accessibility and the user experience. Having values change is hard for screen reader software to pick up, and it may also confuse other users.
It is not an answer, but may be it will help sombody, it is possible to mimic select with details tag. This example is not complete, I used javascript to close list on click
const items = document.querySelectorAll(".item");
// Add the onclick listeners.
items.forEach(item => {
item.addEventListener("click", e => {
// Close all details on page
closeList(item);
});
});
function closeList(item) {
document.querySelectorAll("details").forEach(deet => {
if (deet != this && deet.open) {
deet.open = !open;
console.log(item);
}
});
}
details {
border: 1px solid #aaa;
border-radius: 4px;
}
summary {
padding: .5em 0 .5em .5em;
font-weight: bold;
}
details[open] {
}
details[open] .item {
cursor: pointer;
padding: .5em 0 .5em .5em;
border-top: 1px solid #aaa;
}
details[open] .item:hover{
background-color: #f1f1f1;
}
details[open] .title{
padding: .5em 0 .5em .5em;
border-top: 1px solid #aaa;
}
<details>
<summary>Select your choice</summary>
<div class='title'>
This is attempt to mimic native <code>select</code> tag with html for <code>option</code> tag
</div>
<div class='item'>item 1</div>
<div class='item'>item 2</div>
<div class='item'>item 3</div>
</details>

Ideas for multicolored textbox?

In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.