Reputation: 3
I'm trying to change a form input field (username) to uppercase and to remove all spaces within the text. I know there are a few ways one could do this but I need to figure out how to do this using a function. I need to get the input by it's id and use the toUpperCase method but I cannot figure this out for the life of me. As you might be able to tell, I am new to JavaScript. Any help would be greatly appreciated. Thank you.
HTML:
<div class="login-form">
<h1 class="h1-login">Welcome</h1>
<h4>Please login to enjoy our services</h4>
<form class="login-form" name="login-form" method="post">
<label for="username"><span class="required">*</span>Username:</label>
<input id="username" type="text" name="username" autofocus onkeyup="changeToUpperCase()">
<label for="password"><span class="required">*</span>Password:</label>
<input type="password" name="password" size="8" maxlength="8">
<input class="login" type="submit" value="Login">
</form>
</div>
Here is the JavaScript:
function changeToUpperCase() {
document.login-form.value = document.login-form.value.toUpperCase();
}
This code does not work... and I have no idea how to remove spaces from an input text. Please help me.
Upvotes: 0
Views: 12106
Reputation: 29836
Something like this:
function trimAndUpper(id){
var element = document.getElementById(id);
element.value= element.value.trim().toUpperCase();
}
Add the trim function to a String:
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
Usage: FIDDLE
BTW using str.Replace isn't good. This will replace the first occurance only.
Upvotes: 0
Reputation: 1235
You could try using this:
('text with spaces').replace(" ", "");
Upvotes: 0
Reputation: 690
I'd change the html to this:
onkeyup="changeToUpperCase(this)"
And adjust the function to this
function changeToUpperCase(t) {
var eleVal = document.getElementById(t.id);
eleVal.value= eleVal.value.toUpperCase().replace(/ /g,'');
}
Upvotes: 0
Reputation: 74738
You can try this:
onkeyup="changeToUpperCase(this)"
Then in the script:
function changeToUpperCase(el)
{
el.value =el.value.trim().toUpperCase();
}
Upvotes: 1
Reputation: 3534
function changeToUpperCase() {
document.getElementById("username").value = document.getElementById("username").value.toUpperCase().replace(" ", "")
}
Example here: http://jsfiddle.net/haxtbh/DDrCc/
Upvotes: 0