joby george
joby george

Reputation: 83

After submitting a form to javascript and receiving result , another value cannot be submitted without reloading the page

I wrote a javascript code to find nth prime number, though not efficient it do give the result. However after submitting the value and getting result for first time, i can submit another value on the same page again but i won't get result.

<html>
<head><title>test</title>
</head>
<script type="text/javascript">
function prime(n){
	if(n==1)
		window.alert("2");
	else if(n==2)
		window.alert("3");
	else{

	var arr=[];
	prime=2;
	while((arr.length)!=n)
	{
	 count=0;
	for(i=2;i<prime;i++)
	{
		if((prime%i)==0)
		count=count+1;
	}

	if(count<=0)
		arr.push(prime);

	prime++;
	}
	num=arr.pop();
	window.alert(num);
	}
}
</script>
<body>
<form name="frm">
	<input type="text" name="n" id="id1">
    <input type="button" value="find" onclick="prime(document.frm.n.value)" >
</form>

</body>
</html>

Upvotes: 1

Views: 44

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

You're assigning to prime within your function, but you haven't declared it as a local variable. So it's assigning to the function's variable instead. Add let prime (or var prime for ES5) within the function to make it local.

Your code is also falling prey to what I call The Horror of Implicit Globals: You never declare count or num, so the first time you assign to them, you create globals for them.

Fundamentally: Declare your variables in the scope where you need them (in this case, within the prime function).

Upvotes: 2

Related Questions