In the absence of specific details, my suggestion is to modify your code as follows:
window.alert = function(message){
console.log(message);
}
You can test this out on JS Fiddle here.
This alteration redirects any alerts from alert()
to console.log()
instead.
If you prefer to direct the messages to a specific element instead, you can use the following approach:
window.alert = function(message) {
var output = document.getElementById('output'),
newTextContainer = document.createElement('p'),
text = document.createTextNode(message);
newTextContainer.appendChild(text);
output.appendChild(newTextContainer);
}
Test it out on JS Fiddle here.
Note that using either method will disrupt any existing alert()
functionality on your page. I recommend creating a new function based on the latter example and calling that rather than replacing alert()
directly.
To create a custom alert function that allows you to specify an element for displaying alerts:
function newAlert(message, elem) {
var output = elem ? document.getElementById(elem) : document.getElementById('output'),
newTextContainer = document.createElement('p'),
text = document.createTextNode(message);
newTextContainer.appendChild(text);
output.appendChild(newTextContainer);
}
View the demo on JS Fiddle here.
Edit: In response to the query from the original poster below:
After submitting the form again, I want to replace the previous error message. I don't want to display the same message twice.
If you only wish to show the latest error message and overwrite any previous ones, you can achieve this with the following methods. The first example uses a while
loop to remove the current message in the output
element before appending the new error message:
function newAlert(message, elem) {
var output = elem ? document.getElementById(elem) : document.getElementById('output'),
newTextContainer = document.createElement('p'),
text = document.createTextNode(message);
while (output.firstChild){
output.removeChild(output.firstChild);
}
newTextContainer.appendChild(text);
output.appendChild(newTextContainer);
}
Try it out on JS Fiddle here.
Alternatively, you can simply update the content of the first paragraph element within the output
container if it exists, or create one to display the new message:
function newAlert(message, elem) {
var output = elem ? document.getElementById(elem) : document.getElementById('output'),
textContainer = output.getElementsByTagName('p')[0] || output.appendChild(document.createElement('p'));
if (textContainer.firstChild){
textContainer
.firstChild
.nodeValue == message;
}
else {
textContainer
.appendChild(document
.createTextNode(message));
}
}