Javascript press an input once when HTML loaded and never again - javascript

so I am using a jQuery Ajax updater which uses jinja2 to determine values when a certain value is too I'm attempting to press an input which loads a url linked to flask. However I only want to go to this url once which is an issue as my updater refreshes every 0.5 seconds causing the link to be loaded multiple times.
Snippet of my updater with javascript to press button:
{% elif item['status'] == "pass" and item['api'] == "Yes" %}
<td style="color: #DAA520;">Good</td>
<input onclick="location.href = '/api';" type="hidden" id="popupbtn">
<script>
setTimeout(function () {document.getElementById("popupbtn").click();}, 500);
</script>
This is called every 0.5 seconds in index.html, I only want to press popupbtn once how can I achieve this? I was thinking I could just wait for the element to be visible in index.html and press it then, but how can I do that?

One possible solution is to use localStorage to maintain a status of the page and prevent the redirect on future clicks. In this example, "onclick" is removed from the input element and an event listener checks a stored variable to determine whether or not the redirect happens.
{% elif item['status'] == "pass" and item['api'] == "Yes" %}
<td style="color: #DAA520;">Good</td>
<input type="hidden" id="popupbtn">
<script>
// determine the status of the page
function getPageStatus() {
var pageStatus = 'initial';
if (!(Storage===undefined)) {
if (!(pageStatus===undefined)) {
pageStatus = localStorage.pageStatus
} else {
localStorage.pageStatus = 'initial';
}
}
return pageStatus;
}
// set the status of the page
function setPageStatus(newStatus) {
if (!(Storage===undefined)) {
localStorage.pageStatus = newStatus;
}
}
setTimeout(function () {
// configure an event listener and remove the "onclick" property from the <input /> element
document.getElementById("popupbtn").addEventlistener('click', function(){
var pageStatus = getPageStatus();
if (pageStatus=='initial') {
// once this has been done once, the click will no longer redirect
setPageStatus('loaded');
location.href = '/api'
} else {
alert('The button has been used.');
}
});
}, 500);
</script>
Be sure to read up on Web Storage
Beware that you have to manually control this so that if you want the button to work on a future visit to the page, you will need to reset the stored value. The above method will kill the button click until the user clears their browser.

Given that you appear to be reloading the page in the onClick event (which I'd highly recommend changing to just loading in a hidden div which would allow you to use a global or other document based mechanism), you'll have to use a query string option.
Something like this:
<input onclick="location.href = '/api?fromclick=yes';" type="hidden" id="popupbtn">
<script>
if (window.location.href.indexOf('fromclick') == -1) {
setTimeout(function () {document.getElementById("popupbtn").click();}, 500);
}
</script>

Related

How can I avoid infinite loop when reformatting url hash with Jquery event 'hashchange'

Issue Background
I have set up my webpage to use identifiers with prefix #s- to differentiate anchor links from other page identifiers. The window.location.hash changes to hash which moves the frame to the content in focus but also triggers the hashchange listener causing a loop.
What I've tried
I have it working for whenever the hash has changed but the only instance it does not work is when the same link it pressed (as I use this in the condition to stop the infinite loop). The code for this was:
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
What I want
I'd like to be about to find a condition or method to allow users to select a link to change the hash but also allow them to re-select the same link as many times as they want without causing a loop.
JS
last_hash = ''
function manageHash() {
var hash = $(location).attr('hash');
if($('#s-'+hash.substring(1)).length != 0 && '#s-'+hash.substring(1) != '#s-' ) {
last_hash = hash
window.location.hash = '#s-'+hash.substring(1);
}
}
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
$(document).ready(function() {
manageHash()
})
HTML
<div class="contentSubSectionContainer contentSubSection" id="s-{{ subsection.slug }}">
<h2 class="contentSubSectionFont1Bold">{{ subsection.sub_section_title }}:</h2>
<div class="contentSubSectionContentFont1">
{{ subsection.content_rendered|safe }}
</div>
</div>

How can I exclude a button and a label from form serialization?

I want to use form serialization but exclude a button and a label from the serialization.
This is a version of the javascript I have:
var saveBtn = document.getElementById("btnSaveButton");
var saveLbl = document.getElementById("lblSaveLabel");
var originalFormData = $("#MasterForm").not(saveBtn, saveLbl).serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
//some code
} else {
//some other code
}
});
See: .not(saveBtn, saveLbl)
That is not excluding the button or the label.
Can someone please help me and let me know how I can exclude the button and the label from the serialization?
What essentially happens is I switch the display from the button to the label and back depending on whether the user has made any change to the form.
UPDATE UPDATE
Thank you for the responses ... appears something is amiss ...
There might be too much html to post here ...
Using vb.net. I have a master page, within it is a page called Admin.aspx, and within that is a usercontrol called Bundles.ascx.
In the code of Bundles.ascx I have this javascript:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(prmRequest);
prm.add_endRequest(prmRequest);
function prmRequest(sender, args) {
setupFormChangeCheck("btnSaveBundle", langId);
}
In a master javascript file I have the function setupFormChangeCheck, which looks like this:
function setupFormChangeCheck(txtName, langId) {
try {
savebtnFnctn('dis', txtName, langId)
var originalFormData = $("#MasterForm").serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
savebtnFnctn('en', txtName, langId)
} else {
savebtnFnctn('dis', txtName, langId)
}
});
} catch (err) { }
}
On the same master javascript file I have the function savebtnFunction, which looks like this:
function savebtnFnctn(event, txtName, langId) {
var saveBtn = document.getElementById(txtName);
var saveLbl = document.getElementById(txtName.replace("btn", "lbl"));
if (event == 'en') {
saveBtn.style.display = "inline";
saveLbl.style.display = "none";
} else if (event == 'dis') {
saveBtn.style.display = "none";
saveLbl.style.display = "inline";
}
}
The user control is loaded dynamically, because the same page has multiple use controls and unless I load the one control dynamically, all load ... slows things down incredibly.
Loading a user control dynamically leads to serious postback challenges. So, the vast majority of the user control interactions are handled client side with jquery. For Bundle.ascx this is done in Bundle.js
SOOOOO ....
When the user control is loaded, setupFormChangeCheck fires, which runs the 'dis' (disable) event in function savebtnFnctn.
Here is the problem I noticed today as I tried the code from suggestions above.
When I interact in the Bundle uc, setupFormChangeCheck does not fire from the beginning. What first fires is this line $("form :input").on('change keyup paste mouseup', function ()
And no matter what I do, click in a textbox even without changing anything, leads this: originalFormData != newFormData to be true and the Save button remains enabled ...
I should add that all the controls in the Bundle user control are inside an updatepanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
Long explanation I know, sorry ... if anyone has any idea to solve this, I would be eternally grateful.
Thank you. Erik
The jQuery's .not() method takes selector, not elements.
Also, you are matching the form itself, not the inputs of it.
Since you do know the IDs of the elements to exclude, use this instead:
var data = $("#MasterForm").find("input, textarea, select").not("#btnSaveButton, #lblSaveLabel").serialize();
You select the form.
Then you select the form elements underneath.
Then you exclude the concrete elements from the collection.
Lastly you serialize the results.
NOTE: You should use strict comparison !== instead of !=.

Stop auto triggering a click after page reload

I have code that fill in an input field and then triggers a click on a submit button within a form if a certain text exists in a specific div, so that makes a pages refresh on submit.
I also have a link inside the same form that if clicked it removes the input value that was filled before and also submit the form. Since it submit the form, it triggers a page refresh which leads to executing the first event that fill in the input field and trigger a click on the submit button again.
I want to stop auto triggering that click if the link was clicked by the user.
Perhaps the code explain better...
JS :
$(document).ready(function () {
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
HTML :
<div id="divid">Sampletext</div>
<input type="text" id="inputid" />
<input type="submit" id="button" value="Enter" />
Do This
Answers are greatly appreciated.
It seems you're setting the reloadAfterPageLoad flag, but then you aren't doing anything meaningful with it.
Try replacing the bottom part of your code with something like this;
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1 && sessionStorage.reloadAfterPageReload == true) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
If you set an item in local storage that you use to determine if the click has been triggered, you could use that to determine if it should trigger after reload. local storage persist between page request.
$(document).ready(function () {
var triggered = parseInt(localStorage.getItem('triggered'));
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
if (!triggered) {
localStorage.setItem('triggered', 1);
$("#button").trigger('click');
}
}
});

Exit-pop Javascript setup on WP site with CF7 on particular events

I got some buttons on a website "www.domain.com":
some a href plain text links like "Click Here to request Callback"
some img wrapped in a hrefs to pop-up a Contact Form 7 forms
Contact Form 7 forms with Submit buttons
and I got an Exit-pop script which works if user clicks X button to close the window. This script just asks something like "Are you sure? We got and special offer and click CANCEL" and than he is redirected to special offer page "www.domain.com/sale/".
But problem is if user Orders something 3) he is still got special discount offer! And the logic is - if he click a button 1) or 2) (callback or just button to popup CF7 form but not Submited an order in CF7) it is OK to run a JavaScript for him, and if he entered his phone in CF7 Order form and successfully Submitted it ("on_sent_ok" event for example mb?) he is done and no need to give him an discount offer JavaScript. And of course somehow it should detect that if user on "www.domain.com/sale/" page the script should don’t fire up to prevent double offering.
I got this script on some forum, but:
First it doesn't fun after 1) and 2) buttons hit (even if a user hit "Order" but that he didn't submitted it and just leave the site). And second it is still fires on "www.domain.com/sale/" page.
The script:
<script language="javascript">
(function() {
setTimeout(function() {
var __redirect_to = 'http://domain.com/sale/';
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function() {
document.location.href = __redirect_to;
}, 500);
},5);
return 'WAIT BEFORE YOU GO! CLICK THE *CANCEL* BUTTON RIGHT NOW! PAGE. I HAVE SOMETHING VERY SPECIAL FOR YOU COMPLETELY FREE.';
}
}, 500);
})();
</script>

Page orientation with Jquery?

When button is clicked; if all textboxes aren' t empty on the page it will direct to next page. I made the control it works. But how can i orientate to another page with jquery?
$(document).on("pageinit", "#registerPage1", function () {
$(".nextBtn").click(function () {
if ($(".txt").val().lenght != 0) {
// i want to write codes for orientation registerPage1 to registerPage2 in here
}
$(".txt").each(function () {
if ($(this).val().length == 0 && $(this).next().attr('class') != 'nullInputMsg') {
($(this)).after('<div class="nullInputMsg">this field is required!</div>');
}
else if ($(this).val().length != 0 && $(this).next().attr('class') == 'nullInputMsg')
$(this).next().remove();
});
});
});
Lets assume you have a form named myform housing all your textboxes. Lets also assume that the button with the class nextBtn is inside this form, and triggers the submit behavior for the form.
Like you did , validating the form on the click event of the submit button is fine.However, you'd want to move to the next page only if all the validations pass, so , you should probably leave the redirecting part till the end, by which time you would have determined the results of the validation checks. After that, all that is left to do is
Set the action attribute of 'myform` to point to the required page.(It redirectes to this page)
Return false if the validations fail, or true if they pass from the function handling the click event.
So, your code would look something like
$(document).on("pageinit", "#registerPage1", function () {
$(".nextBtn").click(function () {
var validationPass = true;
$(".txt").each(function () {
if ($(this).val().length == 0 && $(this).next().attr('class') != 'nullInputMsg') {
($(this)).after('<div class="nullInputMsg">this field is required!</div>');
validationPass = false;
}
else if ($(this).val().length != 0 && $(this).next().attr('class') == 'nullInputMsg')
$(this).next().remove();
});
return validationPass;
});
});
Your HTML should probably look like
....
....
<form id="myform" name="myform" action="RedirectToPage.php" method="get">
....
//form content housing the textboxes and button with class .nextBtn
....
</form>
....
....
I suppose that by orientation you mean redirection. You don't need jQuery for redirection. Simple javascript will do the job.
// works like the user clicks on a link
window.location.href = "http://google.com";
// works like the user receives an HTTP redirect
window.location.replace("http://google.com");

Categories