Page orientation with Jquery? - javascript

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

Related

Load file in new window with event listener on form submission while keeping other form validations valid

I have a web form that has a sales force "Web-To-Lead" form action. The end goal is to have the form submit like normal while also loading pdf into a new page.
I have two validations set up for certain form items.
The first one is a captcha validation which looks like so:
var allow_submit = false
function captcha_filled () {
allow_submit = true;
}
function captcha_expired () {
allow_submit = false
}
function check_captcha_filled (e) {
console.log('verify captcha')
if (!allow_submit) {
alert('ERROR: Please verify you are human by filling out the captcha')
return false
}
captcha_expired()
return true
}
(This works as expected.)
The second validation I have is for an input to be :checked in order for the form to submit. That code is as follows:
function fnSubmit() {
if($("input:checkbox[id='chk']").is(":checked") == false){
alert("You must agree to collect and use your personal information.");
return false;
}
}
(This also works as expected.)
The problem comes with trying to integrate my pdf_Download() function while maintaining those validations. Because the form action is already reserved for the web-to-lead, I decided to use an onclick EventListener that generates a new window to open with the desired location. The location uses a <?=$_REQUEST in PHP.
Below is a minimal example of the form and the js I have attempted so far to make this work.
<form action="web-to-lead" method="POST" onSubmit="return fnSubmit() & check_captcha_filled() & pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>
<script>
function pdf_Download(e) {
if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
e.preventDefault()
return false
} else {
document.querySelectorAll('button.bluest').addEventListener("click").window.open('<?=$_REQUEST['bf_file']?>');
return true
}
}
</script>
If something is unclear please let me know.
I believe it will work with this
If it doesn't work please add screenshot devtools I will correct the answer
<form action="web-to-lead" method="POST" onSubmit="fnSubmit() && check_captcha_filled() && pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>
<script>
function pdf_Download(e) {
if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
e.preventDefault()
return false
} else {
window.open("<?=$_REQUEST['bf_file']?>");
return true
}
}
</script>

How to get event.preventDefault to work on dynamic function

I have a form that is split into sections. When the user clicks "continue", I have a jquery script that checks to see if all required fields are filled out. If any aren't, then a box appears with a warning and buttons (They are actually <a> tags) for 'yes' and 'no'. I attach an onclick event to the 'yes' button that triggers a function. The function works, but a # appears in the address bar (website.com/page#), which I'm guessing is because the event.preventDefault(); in my code isn't working.
Here is the function that adds the onclick event:
function checkSection (event, check, goTo) {
event.preventDefault();
var emptyFields = "0";
$("#ia"+check+"Div .check").each(function() {
var val = $(this).val();
if (val == "") {
emptyFields++;
}
});
if (emptyFields >= 1) {
$(".mask").show();
$("#warningBox").show();
$(document).on("click", "#yesBtn", function() {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
$(".mask").hide();
});
} else {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
}
}
Here is the tag I am adding the event to:
<div class="medBtn short">
<div class="btnTbl">
Yes
</div>
</div>
The function I end up calling is like this:
function saveContact(event, val) {
event.preventDefault();
//Do Stuff - This is the function where event.preventDefault(); isn't working
}
Like I said, the function still works, so if it's not something I can get around, that is fine. I just don't like having a # in the address bar.
The event object doesn't exist until the event occurs
You prevent default inside the actual event handler
$(document).on("click", "#yesBtn", function(event) {
event.preventDefault();
....
})

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

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

preventDefault() overruled by window.location

I have process in my website which contains a few steps. To navigate I have "previous" and "next" buttons. These buttons are <a> elements with an href attribute (to visit the previous and next step).
The next button works as a door to the next step, but also to validate some fields in the current step, before it continues.
So this is what happens when clicking the next button:
The href value got saved in a variable $url.
preventDefault() prevents the link from opening the URL.
There are some validation checks done.
If they return "true", the $url will be loaded in window.location.
For some steps I need to do another check to the user with a confirm box. But here comes the problem:
Problem:
When the confirm() returns "false", the user should not go to the next page. But the window.location of function 1 "overrules" the preventDefault() of function 2 now.
1. Default next button function:
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
});
2. Confirm box function:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == false) {
e.preventDefault();
}
});
I would do something like that. If you have any question for the code please ask!
fiddle
// These can be changed for each step if you want or not a confirmation
var needs_confirm = true;
var cb_message = 'Have you specified the dimensions in millimeters?';
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if (needs_confirm === true) {
if (confirm_box(cb_message) === true) {
redirect_window(url);
}
} else {
redirect_window(url);
}
});
function confirm_box(cb_message) {
if (confirm(cb_message) === true) {
return true;
} else {
return false;
}
}
function redirect_window(url) {
if (wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="next_link">link
</div>
Where do you called the dimension-check?
e.preventDefault() only cancel the default action of a button which is submit the form. Regardless of e.preventDefault windows.location will always redirect you.
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
//If dimension isnot prompt{
//windows.location
//}else call dimension prompt
}
});
You can put the windows.location like this:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == true) {
window.location = url;
}
});

Categories