I have a website ( in WordPress ) that uses jQuery to display content ( itself " calculated " in the functions.php ). Basically the content that needs to be displayed based on user criterias is loaded with PHP, and displayed with jQuery.
The thing is the text is displayed in upper case, which doesn't match the design psd. I tried many functions that I found on StackOverflow, but they always made the text capitalize when the user types the data, while I need to capitalize text that is loaded in upper case, and that I need to convert to capitalized.
Here's the code I tried :
$.fn.capitalize = function () {
$.each(this, function () {
var caps = this.value;
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
this.value = caps;
});
return this;
};
$.each( tbllPosts, function( key, value ) {
$('.results').prepend('<div class="col-6"><col="row">'+
'<a href="'+wp.url+'" class="text-center"><h3 class="title">'+value.titre+'</h3></a>'+
'</div>'+
'</div>');
$('.title').capitalize();
});
The content is displayed, what doesn't work is the capitalization. Any help is appreciated, thanks !
Just checked, I have this error :
Uncaught TypeError: Cannot read property 'charAt' of undefined
The .val() method is primarily used to get the values of form elements such as input, select and textarea
You should use text() in your case.
Also, you do not send any arguments to your function. That's why it returns undefined.
I simplified your code ( since you didn't share any html ) so i can make a working example.
I also used trim() to remove the white space from the beginning of the text so that charAt(0) will return the first letter not a white-space.
Check below
$.fn.capitalize = function(t) {
$.each(t, function() {
let caps = t.text().trim();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
t.text(caps)
});
return this;
};
const title = $('.title')
$.fn.capitalize(title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title">
capitalize me
</p>
P.S. what do you mean by Well, the CSS property text-transform: capitalize; doesn't work, ? it doesn't get applied ? have you check the dev inspector ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With