Javascript jQuery strip leading and trailing spaces
I want to trim the value (strip leading and trailing spaces) and make first letter in every word capital. When user leave from the element (blur event)
HTML input as follows
<input id="iptFirstName" name="iptFirstName" type="text"/>
JS piece of code
$(document).ready(function(){
var iptFirstName = $("#iptFirstName");
iptFirstName.blur(validateForename);
});
function validateForename(){
var firstName= $("#iptFirstName")开发者_运维百科.val;
//strip leading and trailing spaces
firstName= $.trim(firstName)
//change first letter in every word to uppercase
firstName= Capital(firstName);
//update input field whit new value
$("#iptFirstName").val(firstName);
}
function Capital(eleValue) {
var eleValue;
if (eleValue != "") {
var firstLetter = eleValue.substring(0, 1).touppercase();
var restOfWord = eleValue.substring(1, eleValue.length).tolowercase();
eleValue = firstLetter + restOfWord;
return eleValue;
}
}
Please understand why it isn't working or maybe have a better approach to solve this problem.
$(document).ready(function(){
var iptFirstName = $("#iptFirstName");
iptFirstName.blur(validateForename);
});
function validateForename(){
var firstName= $("#iptFirstName").val();
//strip leading and trailing spaces
firstName= $.trim(firstName)
//change first letter in every word to uppercase
firstName= Capital(firstName);
//update input field whit new value
$("#iptFirstName").val(firstName);
}
function Capital(eleValue) {
var eleValue;
if (eleValue != "") {
var firstLetter = eleValue.substring(0, 1).toUpperCase();
var restOfWord = eleValue.substring(1, eleValue.length).toLowerCase();
eleValue = firstLetter + restOfWord;
return eleValue;
}
}
try this must work, only few changes done,
var firstName= $("#iptFirstName").val;
to
var firstName= $("#iptFirstName").val();
touppercase
to
toUpperCase
tolowercase
yo
toLowerCase
You can try this $.trim(firstName).replace(/^([a-z])|\s+([a-z])/g, function ($1) {return $1.toUpperCase();})
This would do it -
$(document).ready(function() {
var iptFirstName = $("#iptFirstName");
iptFirstName.blur(function() {
$(this).val(function() {
return $.trim($(this).val()).replace(/(^[a-z]| [a-z])/g, function($0) {
return $0.toUpperCase();
})
})
});
});
Demo - http://jsfiddle.net/ipr101/QvATH/1
You had several errors trought the code
$(document).ready(function(){
$("#iptFirstName").blur(validateForename);
});
function validateForename(){
var firstName= $("#iptFirstName").val();
//strip leading and trailing spaces
firstName= $.trim(firstName);
//change first letter in every word to uppercase
firstName= Capital(firstName);
//update input field whit new value
$("#iptFirstName").val(firstName);
}
function Capital(eleValue) {
if (eleValue != "") {
var firstLetter = eleValue.substring(0, 1).toUpperCase();
var restOfWord = eleValue.substring(1, eleValue.length).toLowerCase();
eleValue = firstLetter + restOfWord;
}
return eleValue;
}
http://jsfiddle.net/b3XhL/
精彩评论