GucciBananaKing99
GucciBananaKing99

Reputation: 1506

Display first and last names first letters in a div with only one input in JavaScript

I am trying to create a text input where you can write your first name and your last name. The first letter of the first name and surname should be displayed in a DIV. The letters should be displayed directly without clicking a button.

For example:

You write "John Doe" in the text field and JD should be displayed in the DIV.

In the end it should look like this: In the end it should look like this

Upvotes: 2

Views: 3547

Answers (3)

Alireza Azimi
Alireza Azimi

Reputation: 152

Try something like this:

let text = ''
document.querySelector("input").addEventListener("input", () => {
  text = document.querySelector("input").value;

  let full_name = text.split(" ");
  let initials = full_name[0][0];
  if (text) {
    if (full_name.length >= 2 && full_name[1]) {
      initials += full_name[1][0];
    }
  } else {
    initials = '';
  }


  document.querySelector("div").innerHTML = initials;


});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
  </div>
  <input type="text">


</body>

</html>

Upvotes: 2

Nikhil Singh
Nikhil Singh

Reputation: 1610

There are two ways to achieve this:-

1 - Text way

const val = document.getElementById('name').value;
document.getElementById('initials').innerHTML = val.split[" "][0] + val.split[" "][1]
<div id="initials"><div>
<input type="text" id="name" value="John Doe">

2 - Image way

Using API to generate an image of the initials,

https://ui-avatars.com/

And set the image as the background of the initials div.

Upvotes: 0

jchua
jchua

Reputation: 414

const extractFirstLetters = function(name) {
  let firstName = name.split(' ')[0];
  let lastName = name.split(' ')[1];

  let firstLetters = firstName[0] + lastName[0];

  return firstLetters;
}

let output = extractFirstLetters("John Doe")

// Output => "JD"

Proceed to set div.innerHTML = output.

More on JS DOM Methods.

Upvotes: 0

Related Questions