I was recently asked how to write a palindrome function where a string entered in a text box is confirmed as palindrome by changing the background colour of the text box.
Following is the code for that. If you want to see it live in action, click here.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title>jQuery Textbox Colour Demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<style type="text/css">
#textbox.green {background-color:green;}
#textbox.red {background-color:red;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#textbox").keyup(function() {
if(($("#textbox").val() == "")) {
$("#textbox").removeClass("red");
$("#textbox").removeClass("green");
}
else {
if(isPalindrome($("#textbox").val())) {
$("#textbox").removeClass("red");
$("#textbox").addClass("green");
}
else {
$("#textbox").removeClass("green");
$("#textbox").addClass("red");
}
}
});
});
function reverseString(strval){
var reversestrval = "";
var len = strval.length;
for (var i = len ; i > 0 ; i--){
reversestrval += strval.charAt(i-1)
}
return reversestrval;
}
function isPalindrome(strval)
{
if(strval == reverseString(strval)) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
Enter string: <input type="text" name="query" id="textbox"/>
</body>
</html>