+ 2
How to have the alert pop up only once in javascript?
The alert keeps popping up for n no of times.
6 Réponses
+ 6
You can use localStorage (not compatible with older browsers):
<script type="text/javascript">
var alerted = localStorage.getItem('alerted') || '';
if (alerted != 'yes') {
alert("My alert.");
localStorage.setItem('alerted','yes');
}
</script>
Or you can use cookies, give a look to this answer for a full example code: https://stackoverflow.com/a/21567127/3625883
+ 5
What type of alert/situation are you dealing with? Many ways to go about it, but if you can throw me more information on what you're trying to accomplish, I can tailor my answer to your situation. Otherwise, Baraa has a good solution for you as well.
+ 5
show your code here, may I can help you
+ 3
@Sandeep
Gotcha. Here is an easy solution for that problem. Have a JS function that'll be called from the onsubmit event of the form. (onsubmit=validateFunc(this)) This function is going to be your validation function. Have it do its validations there and if everything is fine, submit the form from there via ajax or display error to user to fix the input they've entered. Don't forget to prevent default submit event. This will cause your validation to only take place when the submit event takes place, so it won't endlessly loop on you and you can properly handle your inputs prior to submission.
Also, if I recall correctly, I believe HTML5 includes an 'email' type on inputs, so it'll automatically check for the regex of email addresses.
Best of luck!
-------------------
HTML5 added several new input types:
color
date
datetime-local
email
month
number
range
search
tel
time
url
week
^If you set input to email, it'll automatically validate on the submit event and prevent submission if invalid.
By the way, may I suggest that you use a 'tooltip' style error message box or some sort of CSS style popup to inform the user? They're really easy to create, something that's expected by modern standards, and also because JS alerts is probably one of the most annoying things a user faces when dealing with sites using JS. As well, you're able to do a lot more with them, style them as you see fit, and is just less clunky in general.
+ 2
I am trying to validate the registration form. In which there is a field where the email is to be re-entered. If not entered or wrongly entered, there should b alert and this alert does not stop.
0
@Jakob thanks! onsubmit: that's exactly how I did it.. dont know how to use ajax as I am new to JS and I was trying to validate a simple form.. input type: I will try that option ... many thanks