Is it possible to capitalise the first letter of each word in a certain class name using jQuery / javascript? I just want to capitalise the first letter of each word of all the fields marked with the class 'capital'.
I just want it to do it as they type, and I know you can do it with css but this is no good as it is stored in the DB as lowercase still.
Here's a simple jQuery plugin that could do this for you:
$.fn.capitalise = function() {
return this.each(function() {
var $this = $(this),
text = $this.text(),
tokens = text.split(" ").filter(function(t) {return t != ""; }),
res = [],
i,
len,
component;
for (i = 0, len = tokens.length; i < len; i++) {
component = tokens[i];
res.push(component.substring(0, 1).toUpperCase());
res.push(component.substring(1));
res.push(" "); // put space back in
}
$this.text(res.join(""));
});
};
And then call like:
$(".myClass").capitalise();
Here's a working example.
The solution is something like this:
Working Sample: http://jsfiddle.net/Py7rW/7/
$('.captial').each(function(){
var arr = $(this).text().split(' ');
var result = "";
for (var x=0; x<arr.length; x++)
result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
$(this).text(result.substring(0, result.length-1));
});
I think this will work :)
$('.capital').css("text-transform","capitalize");
You can try something like:
$('.capital').each(function() {
var s = $(this).text().split(' ');
for(var i=0; i<s.length; i++) {
s[i] = s[i].substring(0,1).toUpperCase() + s[i].substring(1);
}
s = s.join(' ');
$(this).text(s);
}
I would use the css text-transform:capitalize to avoid having to run this on every keypress,
and change the actual value of the fields on change.
field.value= field.value.replace(/((^| )[a-z])/g, function(a, b){
return b.toUpperCase();
});
Simple Step to capitalize the first letter of each word :
$(document).on('keyup', '#myText', function () {
this.value = this.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
});
You could do something like this. This will capitalize the text in a textbox whenever the text has changed:
$(document).ready(function() {
$('.capital').change(function() {
var arr = $(this).val().split(' ');
var result = "";
for (var i=0; i<arr.length; i++){
result += arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
if (i < arr.length-1) {
result += ' ';
}
}
$(this).val(result);
})
});
You can see a working fiddle here: http://jsfiddle.net/5dMg7/
Related
function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.
I have some text that I am rendering using underscore and it contains pipe character that I am trying to remove.
This is what I have tried
<script type="text/html" id="activityDescriptionTmpl">
<%= formatInput(container.CurrentActivity.ProcessActivityDescription) %>
</script>
this is what the text looks like
This is the text with pipe character at the end|
This id a javascript function I created
formatInput = function (input) {
var arr = [];
var finalInput = '';
if (input.indexOf('|') > 0) {
arr = input.split('|');
for (var i = 0; i < arr.length; i++) {
if ($.trim(arr[i]).length > 0)
finalInput += $.trim(arr[i]) + '<br />';
}
}
else {
finalInput = input;
}
return finalInput;
};
But in this case I get the errorcannot read property 'indexOf' undefined
Is there perhaps a better way of just removing this pipe character
Try newInput = input.replace("|", "");
http://jsfiddle.net/robschmuecker/sGKf3/
I am trying to change a javascript function that uses a inline event handler to one that of one with a more modern approach. I would like to remove the ugly event handler from the actual HTML markup and put it in a modular external javascript file. Here is the test case:
Here is the current code (working fine as far as functionality is concerned
function formatPhone(obj) {
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
for (var i = 0; i < numbers.length; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
What I would like to accomplish is something like this:
var TargetEl = $('[name="pnumb"]');
TargetEl.on('blur', function() {
var UserInput = $('[name="pnumb"]').value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
TargetEl.value = '';
for (var i = 0; i < UserInput.length; i++) {
TargetEl.value += (char[i]||'') + numbers[i];
}
My main focus is to remove the inline js and onblur="" event handler.I also want have the phone number formatted after the targeted El is blurred. Lastly I want this to be called by simply assigning a class of say .pnumbFormat... (Thanks in advance for your help SO!)
Here is the fiddle ... http://jsfiddle.net/UberNerd/ae4fk/
Modify your function to accept string and return string.
function formatPhone(value) {
var numbers = value.replace(/\D/g, ''),
char = {
0: '(',
3: ') ',
6: ' - '
};
value = '';
for (var i = 0; i < numbers.length; i++) {
value += (char[i] || '') + numbers[i];
}
return value;
}
var TargetEl = $('[name="pnumb"]');
TargetEl.on('blur', function () {
$(this).val(formatPhone($(this).val()))
});
DEMO
Even better
Thanks #KevinB for Great improvisation.
function formatPhone(_,value) {
var numbers = value.replace(/\D/g, ''),
char = {
0: '(',
3: ') ',
6: ' - '
};
value = '';
for (var i = 0; i < numbers.length; i++) {
value += (char[i] || '') + numbers[i];
}
return value;
}
var TargetEl = $('[name="pnumb"]');
TargetEl.on('blur', function () {
$(this).val(formatPhone)
});
DEMO
In your HTML, consider adding an attribute so you know which fields to format.
<input value="22" type="text" name="pnumb" data-formatter="phone" />
Then in your JavaScript, you can select those elements and set up the handlers:
$('input[data-formatter="phone"]').each(function (index, element) {
// Add blur handlers or whatever here.
});
This way, you only need to add that attribute to your markup, and your global JS takes care of it. Much less to hook up on a per-page basis.
I thought this would be easier, but running into a weird issue.
I want to split the following:
theList = 'firstword:subwordone;subwordtwo;subwordthree;secondword:subwordone;thirdword:subwordone;subwordtwo;';
and have the output be
firstword
subwordone
subwordtwo
subwordthree
secondword
subwordone
thirdword
subwordone
subwordtwo
The caveat is sometimes the list can be
theList = 'subwordone;subwordtwo;subwordthree;subwordfour;'
ie no ':' substrings to print out, and that would look like just
subwordone
subwordtwo
subwordthree
subwordfour
I have tried variations of the following base function, trying recursion, but either get into infinite loops, or undefined output.
function getUl(theList, splitOn){
var r = '<ul>';
var items = theList.split(splitOn);
for(var li in items){
r += ('<li>'+items[li]+'</li>');
}
r += '</ul>';
return r;
}
The above function is just my starting point and obviously doesnt work, just wanted to show what path I am going down, and to be shown the correct path, if this is totally off base.
It seems you need two cases, and the difference between the two is whether there is a : in your string.
if(theList.indexOf(':') == -1){
//Handle the no sublist case
} else {
//Handle the sublist case
}
Starting with the no sublist case, we develop the simple pattern:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
//Add your element to your list
}
Finally, we apply that same pattern to come up with the implementation for the sublist case:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
if(element.indexOf(':') == -1){
//Add your simple element to your list
} else {
var innerElements = element.split(':');
//Add innerElements[0] as your parent element
//Add innerElements[1] as your child element
//Increment i until you hit another element with ':', adding the single elements each increment as child elements.
//Decrement i so it considers the element with the ':' as a parent element.
}
}
Keep track of the current list to add items to, and create a new list when you find a colon in an item:
var baseParent = $('ul'), parent = baseParent;
$.each(theList.split(';'), function(i, e) {
if (e.length) {
var p = e.split(':');
if (p.length > 1) {
baseParent.append($('<li>').append($('<span>').text(p[0])).append(parent = $('<ul>')));
}
parent.append($('<li>').text(p[p.length - 1]));
}
});
Demo: http://jsfiddle.net/Guffa/eWQpR/
Demo for "1;2;3;4;": http://jsfiddle.net/Guffa/eWQpR/2/
There's probably a more elegant solution but this does the trick. (See edit below)
function showLists(text) {
// Build the lists
var lists = {'': []};
for(var i = 0, listKey = ''; i < text.length; i += 2) {
if(text[i + 1] == ':') {
listKey = text[i];
lists[listKey] = [];
} else {
lists[listKey].push(text[i]);
}
}
// Show the lists
for(var listName in lists) {
if(listName) console.log(listName);
for(var j in lists[listName]) {
console.log((listName ? ' ' : '') + lists[listName][j]);
}
}
}
EDIT
Another interesting approach you could take would be to start by breaking it up into sections (assuming text equals one of the examples you gave):
var lists = text.match(/([\w]:)?([\w];)+/g);
Then you have broken down the problem into simpler segments
for(var i = 0; i < lists.length; i++) {
var listParts = lists[i].split(':');
if(listParts.length == 1) {
console.log(listParts[0].split(';').join("\n"));
} else {
console.log(listParts[0]);
console.log(' ' + listParts[1].split(';').join("\n "));
}
}
The following snippet displays the list depending on your requirements
var str = 'subwordone;subwordtwo;subwordthree;';
var a = []; var arr = [];
a = str;
var final = [];
function split_string(a){
var no_colon = true;
for(var i = 0; i < a.length; i++){
if(a[i] == ':'){
no_colon = false;
var temp;
var index = a[i-1];
var rest = a.substring(i+1);
final[index] = split_string(rest);
return a.substring(0, i-2);
}
}
if(no_colon) return a;
}
function display_list(element, index, array) {
$('#results ul').append('<li>'+element+'</li>');
}
var no_colon_string = split_string(a).split(';');
if(no_colon_string){
$('#results').append('<ul><ul>');
}
no_colon_string.forEach(display_list);
console.log(final);
working fiddle here
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML().indexOf("search string") != -1){test[i].style.color="black";}
Hopefully it's obvious what I'm trying to do - if there is a link on the page that contains the search phrase, change it's color to black. This isn't working though. Any ideas?
Thanks.
innerHTML is a property not a function, so don't use ().
innerHTML is not a function, it is a property. Try doing this instead:
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++)
if(test[i].innerHTML.indexOf("search string") != -1){test[i].style.color="black";}
A cleaner way of doing it would be to use jQuery:
var searchTerm = 'term1';
$('a').filter(function (a) {
if (this.innerHTML.indexOf(searchTerm) != -1)
return true;
return false;
}).css('color','red')
var test = document.body.getElementsByTagName("a");
for (var i=0; i<test.length; i++) {
var newElem = test[i].innerHTML;
if(newElem.indexOf("searchString") != -1){
test[i].style.color="black";
}
}
​innerHTML is no function! It's a property!