-
Problem related to multiple search in Java script
Hi,
In a for loop I am trying repeatedly to search for a given string ("motto") in the string
variable "str". But it never finds a match. But, as far as the logic is concerned it should find "motto" in variable str three times and print it to the screen.
Current output: Nothing is displayed, it doesnt even enter the if loop
Expected output: motto motto motto
The code seems to be correct, but it does not display the ouput in the way it sholud be.
Below is the complete code, can be directly copied to notepad and open in a browser.
Code:
<script language="JavaScript" type="text/javascript">
function T()
{
var key = "motto";
var str = "hello motto test";
var res = " ";
for(var i=0; i<3;i++)
{
alert("in for");
if(str.indexof(key) != -1)
{
alert("inside if");
res += key + " ";
}
else
alert("no match");
}
alert(res);
}
</script>
<form name="search" >
<div align="center">
<input type="submit" onclick="T()"> </div>
</form>
It looks simple, but I think I am missing some thing any help?.
Thanks,
Last edited by Hack; 11-28-2007 at 09:57 AM.
Reason: Added Code Tags
-
I think your logic (if it works) will produce 3 alert notifications which will not be good.
I took the code for some modification to make it document.write, that way, it prints to the page versus using alert.
This is just to prove that it is possible but not providing you with an entire solution.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function T()
{
var key = "motto";
var str = "hello motto test";
var res = str.search(key);
for(var i=0; i<3;i++)
{
if(res != -1)
document.write("In for " + key+'<br>' );
else
document.write("No value returned");
}
}
</script>
</head>
<body>
<form name="search" >
<div align="center">
<input type="submit" onclick="T()"> </div>
</form>
</body>
</html>
-
first Functions in java-script are case sensetive,
indexof() is not a function, should be indexOf()
second once javascripting recive an error it doesn't continue execution of the script; so once it see the indexof and doesn't know how to handle it, it stop the execution and ... as you can se nothing happens.
Hope this can helps.
Similar Threads
-
By bubberz in forum ASP.NET
Replies: 2
Last Post: 08-23-2005, 02:19 PM
-
By Recruitermd in forum Careers
Replies: 0
Last Post: 03-24-2005, 03:53 PM
-
Replies: 3
Last Post: 03-07-2005, 03:34 AM
-
By Richard Berman in forum ASP.NET
Replies: 1
Last Post: 07-19-2001, 10:32 PM
-
By JJ in forum Enterprise
Replies: 1
Last Post: 07-06-2000, 04:50 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|