好的,基本上我需要实现五件事 - 使用JS而不是jQuery。我在这里尝试了几个RegExp代码,但没有一个适用于我。让我先从第一个问题(第1个)开始:
function removeSpaces(str){
return str.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s+/g," ");
}
<html>
<body>
<form action="" method="post" name="myform" onsubmit="removeSpaces(this)">
<div id="nameDiv">
<label for="user_login">User login</label>
<input id="userName" type="text" name="user_login" value="">
</div>
<div id="submitButton">
<input type="submit" value="Submit" name="" onclick="validateForm(), removeSpaces(), firstLetterCaps()">
</div>
</body>
</html>
对于1号,我尝试了这个,但它不起作用:
<html>
<head>
<title></title>
<script type="text/javascript">
function removeSpaces(nameInput){
var nameInput = document.getElementById("userName").value;
return nameInput.replace(/ +(?= )/g,'');
}
</script>
</head>
<body>
<div id="nameDiv" style="border: 1px solid red; text-align: center;">
<label for="user_login">User login</label>
<input id="userName" type="text" name="" value="" required="" onblur="capitalizeFirstLetter(); removeSpaces()">
</div>
</body>
</html>
非常感谢任何帮助!
答案 0 :(得分:1)
试试这个:
<html>
<head>
<title></title>
<script type="text/javascript">
<!--
function checkAndFormat(nameInput){
var el = document.getElementById("userName");
if ( typeof el != "object" ) {
alert("Cannot find element called 'userName'!");
return;
}
var nameInput = el.value;
if( typeof nameInput == "string" ) {
var aryParts = nameInput.split(" "), strFirst, strLast;
for( var i in aryParts ) {
var strTerm = aryParts[i].trim();
if ( strTerm.length == 0 ) {
continue;
}
strTerm = strTerm.toLowerCase();
strTerm = strTerm.substr(0,1).toUpperCase() + strTerm.substr(1);
if ( strFirst == undefined ) {
strFirst = strTerm;
} else if ( strLast == undefined ) {
strLast = strTerm;
}
}
if ( typeof strFirst == "string" && typeof strLast == "string" ) {
el.value = strFirst + " " + strLast;
return;
}
}
throw("Please enter first name and last name!");
}
// -->
</script>
</head>
<body>
<div id="nameDiv" style="border: 1px solid red; text-align: center;">
<label for="user_login">User login</label>
<input id="userName" type="text" name="" value="" required="" onblur="checkAndFormat();">
</div>
</body>
</html>
答案 1 :(得分:1)
function onSubmit(element) {
errorElement = document.getElementById("error");
errorElement.innerHTML = "";
elements = element.querySelectorAll("label > input, label > textarea");
words = elements[0].value.match(/\S+/g) || [];
if(words.length < 2) {
document.getElementById("error").innerHTML += "<br>Name must be at least 2 words."
return false;
}
words = words.map(function(word) {
return word[0].toUpperCase() + word.substr(1);
});
elements[0].value = words.join(" ");
}
function onUpdate(element) {
}
div#error {
color: red;
}
<form onsubmit="return onSubmit(this);">
<label>Name:<br><input type="text" name="userName"/></label>
<br><br>
<label>Comments:<br><textarea name="comment" onchange="onUpdate"></textarea></label>
<br><br>
<input type="submit"/>
</form>
<div id="error"></div>
得到了除了4之外的一切。