I'm trying to make a small script that determines whether inputted text is entirely uppercase, entirely lowercase, or neither. Here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
function caps (p1){
console.log ("yes");
if (p1.toUpperCase() == p1){
alert ("Is uppercase")
}
else if (p1.toLowerCase() == p1){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
</script>
<form id="form1" name="form1" method="post" action="">
<p>
<label>Write something<br />
<input type="text" name="numero" id="numero" />
</label>
</p>
<p>
<input onclick="caps(numero)" type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
However, it doesn't work; the Firefox Web Console insists that "toUpperCase()" is not a valid method. What's happening here?
In your onclick
, you call the function like this: caps(numero)
This isn't passing numero
as a String
. Its passing it as a variable name. An undefined one. .toUpperCase
is a method on String
, and will not exist on undefined
.
Instead, try: caps('numero')
Or, if you're trying to pass the value of your text input:
caps(document.getElementById('numero').value)
Perhaps better yet, build that into your function:
function caps (id) {
var p1 = document.getElementById(id).value
if (p1.toUpperCase() == p1){
alert ("Is uppercase")
}
else if (p1.toLowerCase() == p1){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
That way, you can call it like onclick="caps('numero')"
, passing in the id
of the input whose value you want to UpperCase
Try this way, p1 is input element not your input element's value so compare with p1.value
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function caps (p1)
{
console.log (p1); //see here
console.log (p1.value);
if (p1.value.toUpperCase() == p1.value){
alert ("Is uppercase")
}
else if (p1.value.toLowerCase() == p1.value){
alert ("Is lowercase")
}
else {
alert ("Is mix of both");
}
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label>Write something<br />
<input type="text" name="numero" id="numero" />
</label>
</p>
<p>
<input onclick="caps(numero)" type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
not p1.toUpperCase() == p1
, p1 stand for input
dom element where id="p1",
don't have touppercase
method,only string has this method,so you should use p1.value
document.getElementById(p1)
equals to p1
, p1
is the id name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.