1

Is it possible with jQuery or Javascript to copy the first character of a string that's user generated to another div?

As an example, the contact list on iPhone. The first letter of the contact name is used in the circle adjacent to the name.

With the correct snippet the output would be as follows, where 'First name, Last name' will be different.

<div class="initial">F</div>
<div class="name">First name, Last name</div>

<div class="initial">J</div>
<div class="name">John Smith</div>

I tried to get some ideas from these other posts:

However, I'm not sure where to start and how to output the result to the 'initial' div.

Ken
  • 368
  • 3
  • 11

2 Answers2

4

The simple way to do this is to provide a function to text() of the .initial elements which reads the first character from the sibling .name and returns it, like this:

$('.initial').text(function() {
  return $(this).next('.name').text().slice(0, 1).toUpperCase();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="initial"></div>
<div class="name">Foo Bar</div>

<div class="initial"></div>
<div class="name">John Smith</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    this solution and explanation worked exactly as I hoped. I was so focused on trying to use .slice() correctly I couldn't get my head around working in the targets correctly. – Ken Feb 28 '19 at 10:04
0

a vanilla JS solution i came up with:

https://jsfiddle.net/y0c9be6g/

<div class="initial"></div>
<div class="name">Bob Smith</div>

<div class="initial"></div>
<div class="name">Jim Halpert </div>

<div class="initial"></div>
<div class="name">Billy Baldwin</div>

<script>
var names = document.querySelectorAll(".name");
var initials = document.querySelectorAll(".initial");

function addInitial(item){
 item.previousSibling.previousSibling.innerHTML = item.textContent.charAt(0);
}

names.forEach(addInitial);
</script>
Dan N.
  • 61
  • 1
  • 7