call javascript function only once inside if statment - javascript

In this if statement I can call a function to alert a message if the statement are true but the problem I get the message more that one time every time I click on ok button on the message box I get the same message box, again and again, I want to get the message only one time (I want to call the function only one time in the if statement ) are there any way for that ?
My if statement loop
if(brd_side == COLOURS.WHITE) {
firstmassege();
} else {
secondmassege();
}
My functions :
function firstmassege() {
alert('the first massege');
}
function secondmassege() {
alert('the second massege');
}

This Code should simply work. Hope this would be useful. This displays the first message only once and the second message after the button is clicked for the second time as required.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to test the Function</p>
<button onclick="myFunction()">Click </button>
<p id="demo"></p>
<script>
var executed = false;
function myFunction() {
if (!executed){
firstmessage();
executed = true;
} else {
secondmessage();
}
}
function firstmessage() {
alert('the first message');
}
function secondmessage() {
alert('the second message');
}
</script>
</body>
</html>

How about using a flag to store the status. Please see the code below.
$('#btn').click(firstmessage)
var clicked = false;
function firstmessage() {
console.log('other statements...')
if(!clicked){
alert('the first massege');
}
clicked = true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">click</button>
In your case it will be like below
var flag =false;
if (!flag){
firstmessage();
flag = true;
}

You can use one in jquery:
$('#myButton').one('click', function(){ alert('Hi!');});

Related

disabling a button while running a function

I have a function in Javascript which is called by clicking a button and it takes approximately one minute to be finished. How can I disable the button after one click and enable it again after function is finished?
I need this process to prevent spamming.
I tried the following piece of code, but it is not working. It is still possible to click the button several times.
Javascript:
function myFunc()
{
document.getElementById("Btn").disabled = true;
\\do something for one minute
document.getElementById("Btn").disabled = false;
}
html:
<button type="button" id="Btn" onclick="myFunc()">Generate!</button>
Your code is working fine. Maybe your function runs quickly that's why it appears as you can spam.
If you're calling function thru ajax, make sure async is false (default is true)
function myFunc() {
document.getElementById("Btn").disabled = true;
setTimeout(function() {
console.log('hey');
document.getElementById("Btn").disabled = false;
}, 1000);
}
<button type="button" id="Btn" onclick="myFunc()">Generate!</button>

Submit Form Only once

[Repeatedly I'm getting Notifications]. Actually, I just want to run the PHP script in cron job and i found two alternatives to submit form automatically and to click button automatically.
But these scripts are repeatedly doing it. I need to run only once.
One by using form id:
<script>
function submitForm() {
document.getElementById("form").submit();
}
window.onload=submitForm;
</script>
Another by using Button id:
<script>
jQuery(function(){
jQuery('#submit').click();
return false;
});
</script>
Can Anyone Help Me...
use sessionStorage.
<script>
function submitForm() {
var IsSubmit = sessionStorage.getItem("IsSubmit") || "N";
if(IsSubmit === "Y")
{
document.getElementById("form").submit();
sessionStorage.setItem("IsSubmit","Y")
}
}
window.onload=submitForm;
</script>

onclick event not firing based on boolean flag

I'm working on some code where if a user clicks on a particular button, that person is NOT presented with an exit popup upon exiting the page. The way I'm doing it is by setting a flag whenever the user clicks on the button. However, my code isn't working as expected: The popup loads whether or not the button is clicked. I don't understand why.
Edit: Help!
<!doctype html>
<html>
<head>
<title>Test!</title>
<script>
var bool = false;
var config = new Object();
config.surveyID = 3155031;
config.takeSurveyURL = 'http://www.supporterfeedback.org/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.showFooter = true;
// document.getElementById("btn").onclick = function()
// {
// bool = true;
// };
function flag() {
bool = true;
}
if (!bool) {
window.onbeforeunload = function () {
QP_popupMain();
};
}
</script>
<script language="javascript"
src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"
type="text/javascript"></script>
<noscript>
Start Survey
</noscript>
</head>
<body>
<a href="http://google.com"><img id="btn" onclick="flag()"
src="http://kelowna.directrouter.com/~jeasprco/wp-content/uploads/2012/05/PanicButton2.png"/></a>
<p>Hello, this is a test!</p>
</body>
</html>
I think window.onbeforeunload = function () is operating as soon as the page loads, so what is inside if(!bool) is executing on the button press.
Try changing these two lines:
// var bool = false;
var bool;
// if (!bool) {
if (bool == false) {
You're testing the flag once, when you assign the .beforeunload handler when the page is loaded. Calling flag() doesn't re-execute that code. You need to test it when the function is called.
window.onbeforeunload = function() {
if (!bool) {
return "You haven't clicked the button, do you really want to leave?"
}
}

Javascript div output in html not working

I am using this innerhtml property to print my output from javascript into a div in html. I have checked other topics with the same problem, but nothing seems to work.
The following code is all between the 'body' tags in my html.
Code:
<script> function firstGame(); </script>
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML('<p>First test</p>');
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
Let's talk about page rendering upon initialization and global scope. A scope is the context in which values and expressions are "visible," or can be referenced. The global scope is the context for the whole document. If a value or function is declared here it's visible in every function or expression.
The JavaScript in your page is being parsed one script block at a time. When the script block is parsed without errors the script block is transferred into the global scope. The thread (stored in the window object) where all public values and expressions are available.
Functions are parsed first, then the rest of the block. However script blocks are parsed one at a time I wrote earlier. So if you make a call to a function not yet in the global scope since it's in another script block that hasn't been parsed yet your code will fail and throw and undefined error.
Consider this:
<script>
function test()
{
alert(1);
}
test();
</script>
A nice alert is shown. the function test is parsed first and test is executed thereafter.
<script>
test();
function test()
{
alert(1);
}
</script>
This also works. Since functions are parsed first test() still works and alerts 1.
<script>
test();
</script>
<script>
function test()
{
alert(1);
}
</script>
This however won't work. Since the function test in the second script block isn't yet parsed calling test() will result in a script error.
<script>
function test()
{
alert(1);
}
</script>
<script>
test();
</script>
This does work. The function is declared first and added to the global scope. In the second script block test() looks for a function test in the global scope, finds it and executes it.
This is the explanation above applied to your code:
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
// Do you really need this?
//Confirm returns a Boolean (true or false), you can do something with the result. If not just show an alert or nothing. Latter is preferred.
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
//You should make this more robust. What if someone enters "asaaslk". Use a select box with birth years.
if (age < 13)
{
document.getElementById('outputgame').innerHTML = "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML = "Sweet, Let's go!";
}
}
</script>
<script> function firstGame(); </script>
<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
HTML
<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
javascript
<script type="text/JavaScript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML='<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game.You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>
Two problems: You named your function the wrong name?, and you are calling innerHTML as a function instead of assigning it a value.
Also, where is functionGame() defined? You cannot use forward declarations like in C.
function firstGame() {
var output = document.getElementById('outputgame');
var text = '';
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = parseInt(prompt("What is your age?"), 10);
if (age < 13) {
text = "You are to young to play this game. You can proceed, however I do not take any responsibility.";
} else {
text = "Sweet, Let's go!";
}
document.getElementById('outputgame').innerHTML = text;
}
<div id="outputgame"></div>
<button onclick="firstGame()">Starten</button>

How to Prevent to redirect page before javascript alert click?

I am using below javascript code. I want to stay on same page till user click on alert.
After click on alert page should redirect to SomePage.aspx
<script type="text/javascript">
function myFunction() {
alert("Some text...");
window.location = 'SomePage.aspx';
}
</script>
Please let me know what I missed here.
Thanks.
Instead of alert i think you need confirm box :-
<script type="text/javascript">
function myFunction() {
var conf = Confirm("Some text...");
if(conf == true){
window.location = 'SomePage.aspx';
}
else{ }
}
</script>
Try Like this
Script
<script type="text/javascript">
window.alert = function (al, $) {
return function (msg) {
al.call(window, msg);
$(window).trigger("okbuttonclicked");
};
}(window.alert, window.jQuery);
$(window).on("okbuttonclicked", function () {
redirect();
});
function redirect() {
window.location.href = "http://www.google.com";
}
function myFunction() {
alert("Some text...");
}
</script>
Html
<input type="button" onclick="myFunction()" value="Click" />
Note :- This function is execute on every alert ok button. But you also pass some additional parameter for preventing to execute.
And i also recommended to use confirm instead of this.

Categories

Resources