Reputation: 7030
I've come across a very bizzare behavior on my Chrome. The following code causes the page to be refreshed on Chrome when I click on the add button which is not what I want it to do:
function addSpamAddr()
{
var email = prompt("Add Spam Address","");
if (email == null || email == "")
return false;
var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regex.test(email) == false) {
alert("You must enter a valid E-Mail address");
return false;
}
var listBox = document.getElementById('spamList');
for (var x = 0; x < listBox.options.length; x++) {
if (listBox.options[x].value == email || listBox.options[x].text == email) {
alert("Already blocked address");
return false;
}
}
var selectBoxOption = document.createElement("option");
selectBoxOption.value = email;
selectBoxOption.text = email;
listBox.add(selectBoxOption);
return false;
}
...
<button style="margin-right: 20px;width:60px" onclick="addSpamAddr()">Add</button>
The code works perfectly fine on Internet Explorer. I've created a minimal example to further investigate the issue:
function addSpamAddr()
{
return false;
}
...
<button style="margin-right: 20px;width:60px" onclick="addSpamAddr()">Add</button>
Still causes refresh on Chrome.
How can I prevent the refresh?
Edit: After I added the return statement inside the onclick event, the page no longer refreshes on the minimal example I created.
<button style="margin-right: 20px;width:60px" onclick="return addSpamAddr()">Add</button>
However, the page would still refresh if I apply my original code. Particularly, this part causes it:
var listBox = document.getElementById('spamList');
var exists = false;
for (var x = 0; x < listBox.options.length; x++) {
if (listBox.options[x].value == email || listBox.options[x].text == email) {
alert("Already blocked address");
return false;
}
}
How do I fix this?
Upvotes: 2
Views: 3494
Reputation: 176896
write like this
function addSpamAddr()
{
return false;
}
...
<button style="margin-right: 20px;width:60px" onclick="return addSpamAddr()">Add</button>
you for got to write "return addSpamAddr()"
in your html cod which is updated by me
Upvotes: 6