Stop auto triggering a click after page reload - javascript

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');
}
}
});

Related

Javascript press an input once when HTML loaded and never again

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>

MVC - Issue with users double-clicking Submit button

I have a number of pages in my MVC app where the user clicks a Submit button to post a form. Sometimes users will click Submit and since nothing happens immediately, click it again. Therefore, the form submits twice. To prevent this, I have the following JavaScript code:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
This code disables the Submit button so the user cannot click twice. This works fine. However, if there are client side validation errors on the form, the Submit button gets disabled but the form is never posted, and now the user cannot post the form. Is there a change I can make to the JS code to detect if there were client side validation errors, and, if so, I either don't disable the Submit button, or reenable it?
If you are using jQuery Validate, you can check to see if the form is valid before disabling the button:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
You can try something like this:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
Switch it around.
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});

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");

JS/Ajax: grab input field value without refresh or button click

I am currently using js function to submit data without page refresh or button click. The input field is inside tab #2 that executes the js once the user stops typing. The problem is that the js is making the page refresh thus taking me back to tab#1. How can I prevent the page from refreshing? I thought i had included the necessary code in the JS function to stop this. EXAMPLE
<script>
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//submit definition once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php#tab-2', form, function(data){
var x = $(data);
$("body").html(x);
});
return false;
});
return false;
});
</script>
try changing this line
//do your submit here
$("#ytVideo").submit()
to
$("#ytVideo").trigger("submit");
i believe the problem is that you define what submit should do after the form has been submitted this causes the page to reload.
Edited
try this change
$('#ytVideo').submit(function(event){
event.preventDefault(); //prevent page refresh
event.stopPropagation(); //+
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php#tab-2', form, function(data){
var x = $(data);
$("body").html(x);
});
//- return false;
});
//- return false;
made some changes
Instead of .submit() you should use .triggerHandler('submit'). Docs and related question.

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories