Link to home
Start Free TrialLog in
Avatar of dimsouple
dimsouple

asked on

Convert ALL CAPS to Camel Case - Ajax/jQuery

I have an html form with a subject ALL CAPS from DB and I need to quickly convert it to camel case before saving back to Database.

<input id="subject" name="subject" Value="THIS SUBJECT IS ALL CAPS"  />

I need an ajax function that will convert $('#subject').val(); to Camel Case on the form

I would like to call it using a link on the form:
<a href="javascript:CamelCaseIt('subject')">Subject CaMel Case</a>

= = = =

I would also like to force a lower case action on $('#message').val(); for the users tho post the entire message ALL CAPS. If the function can replace 'i' with 'I' and capitalize the start of paragraphs automatically that would be more than great.

Hope you can help.
Avatar of dimsouple
dimsouple

ASKER

I saw them before asking here. noticed the function but not clear on how to implement it for my use.

How to I implement, click a link, call the function, switch input to camel case on form?
did you checked if they work as is? I mean, if you use them independently in a separate application, do they work?
I notice the function but how do I call it?
please give me an example.

Like this?
<a href="javascript:CamelCase('subject')">convert to camel case</a>

I am not as smart as you think :)
just try this simple example

<script>
var string = "any string you want to camel case"; //
//call that method here and alert the result
</script>
ASKER CERTIFIED SOLUTION
Avatar of designatedinitializer
designatedinitializer
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Better still... if you wanted it to act 'as-you-type', do it like this:
<html>
<head>
<script>
function CamelCaseIt(it){
	var textin = document.getElementById(it).value;
	var textout = "";
	for(i in textin){
		if(i==0 || textin[i-1]==" ") textout+=textin[i].toUpperCase();
		else textout+=textin[i].toLowerCase();
	}
	document.getElementById(it).value = textout;
}
</script>
</head>
<body>
<form name="form1" action="" method="post">
<input type="text" id="subject" size="40" name="subject" Value="THIS SUBJECT IS ALL CAPS"  onkeypress="CamelCaseIt('subject');"/>
<input type="submit">
</form>
</body>

Open in new window

...the only change to the previous version is that this gets called with every keypress.
But you might want to apply it right from the beggining on page load.
For that, you'll be safer either doing it in the server, or using jQuery in order to apply this function on $(document).ready
Take a look at this jsfiddle.

The function is quite simple:

function properCase(value) {
    return value.replace(/\b(\w)(\w*)?\b/g, function() {
        return arguments[1].toUpperCase() + arguments[2].toLowerCase();
    });
}

Open in new window