Marius
Marius

Reputation: 499

Convert text from uppercase and mixed to capitalize inside a div

In a WordPress page, inside a div, I want to convert text from uppercase and mixed to capitalize. Data are collected by a form where users use lowercase, uppercase and mixed.

CSS is not a solution because in 2017 CSS is not able to convert uppercase to capitalize.

I'm a beginner in JS and jQuery, please be patient.

My script & my div:

<script>
jQuery.fn.capitalise = function() {
    return this.each(function() {
        var $this = $(this),
            text = $this.text(),
            split = text.split(" "),
            res = [],
            i,
            len,
            component;
        for (i = 0, len = split.length; i < len; i++) {
            component = split[i];
            res.push(component.substring(0, 1).toUpperCase());
            res.push(component.substring(1).toLowerCase());
            res.push(" "); // put space back in
        }
        $this.text(res.join(""));
    });
};


$(".domecap").capitalise();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="domecap">ADDRESS: STR. mihai BRAVU, nUmBER 196</div>

Upvotes: 0

Views: 876

Answers (3)

Blue Boy
Blue Boy

Reputation: 610

Try arranging your html file in the following order, as well as putting the line $(".domecap").capitalise(); inside a $(document).ready() function:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script>
  jQuery.fn.capitalise = function() {
      return this.each(function() {
          var $this = $(this),
              text = $this.text(),
              split = text.split(" "),
              res = [],
              i,
              len,
              component;
          for (i = 0, len = split.length; i < len; i++) {
              component = split[i];
              res.push(component.substring(0, 1).toUpperCase());
              res.push(component.substring(1).toLowerCase());
              res.push(" "); // put space back in
          }
          $this.text(res.join(""));
      });
  };


  $(document).ready(function() {
    $(".domecap").capitalise();
  });
</script>

<div class="domecap">ADDRESS: STR. mihai BRAVU, nUmBER 196</div>

Upvotes: 2

Giovan Cruz
Giovan Cruz

Reputation: 721

You dont need to use jquery to do this. Why not CSS and javascript can do? Like this:

var str = document.getElementById('domecap');
var res = str.textContent.toLowerCase();
str.innerHTML = res;
#domecap {
  text-transform: capitalize
}
<div class="domecap" id="domecap">ADDRESS: STR. mihai BRAVU, nUmBER 196</div>

Upvotes: 0

Aayush Kumar
Aayush Kumar

Reputation: 57

try using this simple jQuery statement instead:

$(".domecap").text($(".domecap").text().toUpperCase());

this will get the text inside your div, convert it into uppercase and then apply onto the specified div.

Upvotes: 0

Related Questions