How to automatically change the input to sentence case as the user types in Angular 8

Hey guys, I'm having an issue with my input field. I want the text to display in sentence case as I type, but it keeps showing up in title case. For example, if I type

"hello hai how are you"
, it displays as
"Hello Hai How Are You"
. However, I would like it to appear as
"Hello hai how are you"
. If a user types using CapsLock then that should take priority.

Check out the DEMO here:

DEMO

Take a look at DEMO2 with Pipe:

Pipe Used

Here is the HTML code snippet:

<div class="col-md-6 mb-3">
    <label for="input1">Input Field to be in sentence case</label>
    <input  type="text" class="form-control text-capitalize" id="input1" placeholder="Name"
     formControlName="name"
     name="name"
      required />
  </div>

And here is the second HTML code snippet:

<form [formGroup]="myForm">
    <input formControlName="myNumber| titleCase" />
</form>

This is the corresponding TypeScript code:

this.myForm = this.fb.group({
      myNumber: ["hello hai how are you"]
    });

Lastly, here is the pipe.ts file content:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: "titleCase" })
export class TitleCasePipe implements PipeTransform {
  public transform(input: string): string {
    console.log(input);
    if (!input) {
      return "";
    } else {
      return input.replace(
        /\b((?!=|\,|\.).)+(.)\b/g,
        first => first.substr(0, 1).toUpperCase() + first.substr(1)
      );
    }
  }
}

Answer №1

One way to achieve the desired effect is by utilizing .toUpperCase(), .toLowerCase(), and .substring():

function adjustText(){
  var input = document.getElementById("input");
  input.value=input.value.substring(0,1).toUpperCase()+input.value.substring(1).toLowerCase();
}
<input id="input" type="text" oninput="adjustText()">

This function ensures that the first letter is capitalized while the rest are in lowercase.

var input = document.getElementById("input");
function adjustText(){
  
  input.value=input.value.substring(0,1).toUpperCase()+input.value.substring(1).toLowerCase();
}
input.addEventListener("keyup", function(event) {

  if (event.getModifierState("CapsLock")) {
    input.value=input.value.toUpperCase();
  }else{
    adjustText();
  }
});
<input id="input" type="text" oninput="adjustText()">

Additionally, you can use an event listener to handle capitalization when CAPS LOCK is active.

In scenarios where multiple input fields require the same functionality:

var inputs = document.getElementsByClassName("input");
function adjustText(){
  for(var i = 0; i < inputs.length; i++){
      inputs[i].value=inputs[i].value.substring(0,1).toUpperCase()+inputs[i].value.substring(1).toLowerCase();
  }
}
<input class="input" type="text" oninput="adjustText()">
<input class="input" type="text" oninput="adjustText()">
<input class="input" type="text" oninput="adjustText()">

Answer №2

Here is a possible solution for you:

Your code in the HTML file:

<input type="text" class="form-control" id="input1" placeholder="Name"
        formControlName="name"
        name="name"
        #name
        required 
        (input)="handleInputChange(name.value)"/>

Your implementation in the TypeScript file:

handleInputChange(val: string){  
  val = val.substr(0,1).toUpperCase() + val.substr(1);
  this.form.name.setValue(val);
}

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

jQuery's click event on dynamically generated AJAX elements sometimes fails to trigger randomly

When I use the getData() function to retrieve ajax content, it dynamically adds elements based on the JSON response from the server. The code snippet below shows how the elements are added: $("#list").append('<div class="ui card fluid" id="' ...

Tips for displaying an uploaded image using the Valums file uploader

I recently implemented the Andrew Valums File Uploader on my website and it's functioning as expected. I am now looking to modify it so that instead of displaying just the uploaded filename and size, it will show the uploaded picture directly in the b ...

Implementing an inline cache for <script> tags that load AJAX content

Looking for a way to cache <script src> received through AJAX requests? Currently, each call attempts to load the src via AJAX by default. However, the issue is that this script remains constant throughout the session and only needs to be re-evaluate ...

What is the best way to determine if the form has been submitted?

I am working on a React form and need to determine when the form has been successfully submitted in order to trigger another request in a separate form. const formRef = React.useRef<HTMLFormElement>(null); useEffect(() => { if (formRef &a ...

Javascript is throwing a reference error because it can't find a definition for StringBuilder

I have a JavaScript function that utilizes a string builder function. It works smoothly in most major browsers like IE8+, Chrome, and Firefox but occasionally I encounter an error stating "stringbuilder is not defined". This issue seems to only affect cert ...

Menu Overlay (jQuery/CSS)

I am in the process of developing a website that is optimized for both mobile and desktop devices. I am currently brainstorming ideas for the main navigation, which I envision as an overlay that slides down similar to . However, I am struggling to create ...

Inject "incorrect" information using jQuery

I am dealing with the following constellation: <dl> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> </dt> ...

What method can be used to dynamically resize two side-by-side iframes in proportion to a specific ratio?

Hey, I've got this code snippet: So there are two iframes positioned side by side with a specific ratio as indicated in the link provided. My aim is to maintain that ratio regardless of the screen size where it's viewed. The first iframe is named ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...

What would the equivalent Javascript implementation look like for this Python code that decodes a hex string and then encodes it to base64?

Currently, I am facing the challenge of transferring code from a Python script that decodes and encodes a string using a series of decode() and encode() functions. In Python, the code appears as follows: import codecs input = '3E061F00000E10FE' ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

The callback function inside the .then block of a Promise.all never gets

I'm currently attempting to utilize Promise.all and map in place of the forEach loop to make the task asynchronous. All promises within the Promise.all array are executed and resolved. Here is the code snippet: loadDistances() { //return new Prom ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

What is the best way to display text outside of the current div container?

When I include the "Y" in the code snippet below, $title1 and $title2 are positioned outside of the div and centered against the width of the page. However, without the "Y", the text shifts up and aligns with the address class instead. It's puzzling w ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

Variables for HTML comment form using PHP mail

How do I properly pass HTML form variables to a PHP mailer? The PHP code is: $comment = $_POST['comment']; $email = $_POST['email']; $to = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60131313 ...

Steps for Embedding an HTML Page into a Tab using jQuery

Within the tab labeled class=plots-tabs-heatmap, I am attempting to insert a new page using the code below. However, instead of seeing tmpdata/page2.html displayed on the tab, nothing appears. $('#plots-tabs-heatmap').html("tmpdata/page2.html"); ...

Implement a custom email template for the contact form utilizing Express and Sendgrid

I have set up a basic contact form that utilizes the Node Sendgrid helper library for sending emails. My goal is to incorporate a template email/contact.jade that will convert to HTML and include the necessary context. I understand that this template shou ...

Changing the target to a nested component within Angular 4

Within my Angular 4 project, I have a component that is nested inside another. This inner or child component consists of a button, an input field, and a drop-down list. When the button is clicked on the parent page, both the input field and the drop-down ...

How can I modify the navbar-collapse in Bootstrap to alter the background color of the entire navbar when it is shown or open on a mobile screen?

Can anyone tell me how to change the background color of the navbar when the navbar-collapse is displayed? I want one background color when the navbar-collapse is shown and a different color when it's collapsed. Is there a way to achieve this using C ...