Reputation: 57
i'm having a hard time validating a text field that must have a specific word in it. For example i have typed a test page that requires the user to type 'hello' if they don't there will be an alert.
I have tried using indexOf, but it fail to work in my case. May i ask what went wrong? and is there any other way of validating such scenario? I would prefer to use vanilla javascript if possible. Thanks.
<html>
<head>
<script type="text/javascript">
function checkText()
{
var text1 = document.getElementById("intro").value;
var text2 = 'hello';
if(text1.indexOf(text2) > -1){
alert("Say hello");
return false;
}else{
alert("Okay!");
}
}
</script>
</head>
<body>
Introduce yourself <input type="text" name="intro" id="intro"> <input type="button" value="Click" onClick="checkText()">
</body>
</html>
Upvotes: 1
Views: 1250
Reputation: 94499
You must get the value inside the function since it will not be available when the script is loaded. Also if you want to alert Say hello
when hello is not present, change the conditional to check for text1.indexOf(test2) == -1
:
var text2 = 'hello';
function checkText()
{
var text1 = document.getElementById("intro").value;
if(text1.indexOf(text2) == -1){
alert("Say hello");
return false;
}else{
alert("Hello " +text1);
}
}
JS Fiddle: http://jsfiddle.net/J4eGw/
Another thing to note, you should avoid attaching events inline within the HTML. You can use the following to attach the events within the script.
HTML
Introduce yourself <input type="text" name="intro" id="intro">
<input id="btnCheck" type="button" value="Click">
Javascript
var text2 = 'hello';
addEvent(window, "load", function(){
addEvent(document.getElementById("btnCheck"), "click", checkText);
});
function checkText()
{
var text1 = document.getElementById("intro").value;
alert((text1.toLowerCase().indexOf(text2) == -1) ? "Say hello":"Okay");
}
function addEvent(element, evnt, funct){
if (element.attachEvent){
//for early IE versions
return element.attachEvent('on'+evnt, funct);
}else{
//for modern browsers
return element.addEventListener(evnt, funct, false);
}
}
JS Fiddle: http://jsfiddle.net/J4eGw/2/
Upvotes: 2
Reputation: 35984
var text2 = 'hello';
function checkText(){
text1 = document.getElementById("intro").value;
if(text1.indexOf(text2) > -1){
alert("Say hello");
return false;
} else {
alert("Hello " +text1);
}
}
<
You will need to ensure that the new value of text1 is obtained on each click, not just when the script loads.
Upvotes: 0
Reputation: 7426
text1
isn't defined to the latest value when you're checking it, so you should do this instead:
var text2 = 'hello';
function checkText()
{
var text1 = document.getElementById("intro").value;//updates every time you check
if(text1.indexOf(text2) > -1){
alert("Say hello");
return false;
}else{
alert("Hello " +text1);
}
}
</script>
</head>
<body>
Introduce yourself <input type="text" name="intro" id="intro"> <input type="button" value="Click" onClick="checkText()">
</body>
Upvotes: 0