Hot to re-active preventDefault function in javascript - javascript

When user clicked on submit button, I need to check some validations before submition. If entered data is not valid page should not be submit.
$(document).ready(function() {
$("#colomnChange").submit(function(e) {
var testA = 1;
if (testA == 1) {
testA = 2;
//e.preventDefault();
return false;
} else {
return true;
}
});
});
I can stop the submition using priventDefault function in js. But again user clicked on submit button after correct the wrong data, page should be submit well. How can I re-active the default function.

The answer is: you always go into the first if (because you set the variable to 1 then check if it equals 1, which is always true)
Change testA = 1 to testA = 2 and your event will go into the else which does not have the preventDefault() method so your event will carry on

Related

Prevent beforeunload function from executing if submit button is clicked

I have the following function that gives a warning to the user if they are exiting the page when the $('.article_div textarea') form field is populated.
$(window).on('beforeunload', function(event) {
var unsaved = "Are you sure you want to exit?";
var text = $('.article_div textarea').val();
if (text.length > 0){
return unsaved;
}
});
However, I would like to prevent this popup from executing when they click the submit button to the actual form.
How can I ammend the function to account for this? The element of the submit button is
$('button.submit_post').
You can create a boolean which gets positive when you click on submit Or remove the event of unload when clicked. The code will be as follows:
var isSubmitClicked = false;
$('button .submit_post').on("click",onClick);
function onClick(e){
isSubmitClicked = true;
}
$(window).on('beforeunload', function(event) {
if(isSubmitClicked){
isSubmitClicked = false;
return;
}
// Rest of your method.
}
How about binding a event handler to the submit event instead of the submit button element?
Maybe like this:
var submitted = false;
$('form').on("submit", function() {
submitted = true;
console.log('submitted');
});
$(window).on('beforeunload', function(event) {
if(submitted){
submitted = false;
console.log('aborted because of submit');
return;
}
console.log('rest of code');
// Rest of your method.
});

detailed conditional submit preventDefault

I've spent some time looking around and trying multiple solutions without luck, while attempting to streamline a form to create a pseudo bulk process.
Essentially I simply need to prevent default on a submit button, but to trigger it if several subconditions are met, at least one of which uses an ajax call.
I've tried variations of e.preventDefault, $('#form').submit(false); and I can either get the validation to occur, or the form to submit, but never both in the right places. (for example it will submit without checking for duplicate entries)
Here's a summed up version of what I've been attempting.
This is the main variable which holds the first part of the check:
var verifyValue = function() {
// this stops the form, and then things validate fine.
$('#add-item-form').submit(false);
//but then I need to get it started again to submit valid entries
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
This is where it is called:
$("#verify-value").click(verifyValue);
Below is a shorthand of the conditional being run:
var checkedValue = function(items) {
if(items.length == 0){
// success conditions
}
else {
//this was just one attempt
$('#form').submit(false);
if( /* sub condition of data passed from JSON array */){
//condition creates new form which upon action sends AJAX call
}
else
{
//second error condition
}
}
};
What I'm trying to do is to have if any of the subconditions occur, to have it stop the submit button (e.g. preventDefault behavior) and if it does not have any of these, to allow the submission of the form
It feels like it should be simple, however no matter where I do this, including using $(this).unbind('submit').submit() It doesn't work right.
Either the validation occurs correctly and nothing submits, or everything submits even if it's not supposed to.
I feel like modifying var verifyValue will work but I'm not sure how to get the conditional statements bound into an event.
Edit:
Okay, so I was guilty of seriously overthinking this issue, and came up with a solution which I will put below (in case anyone is interested)
Since your validation includes an async step, it'd be easier to just stop the form submission right away.
Then call your validation function, which will set the validation state of the form in a "global" state (maybe just a closure of the event handler). If the validation is fine, submit the form, else just show the validation error.
// You'll need to reset this if an input changes
var isFormValid = false;
$("#form").on('submit', function(e) {
if (isFormValid) {
return true;
}
e.preventDefault();
validateForm(function(valid) {
if (valid) {
isFormValid = true;
$('#form').submit();
}
});
});
function validateForm(cb) {
var form = $('#form');
// do some synchronous validations on the form inputs.
// then do the async validation
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
jQuery
.getJSON(
'{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()})
)
.done(function(result) {
if (checkedValue(result)) {
cb(true);
} else {
cb(false);
}
});
} else {
cb(false);
}
}
How about this approach, here's a simple skeleton:
$('#form').submit(function(e){
var formError = false;
// set formError to true if any of the checks are not met.
if(some condition) {
// do a conditional check
formError = true;
} else if(another condition) {
// do another conditional check
formError = true;
}
if(formError) { // stop form submission of any of the conditions are not met.
return false; // same as e.preventDefault and e.stopPropagate()
}
});
It turned out I was seriously overthinking this issue. It was a lot easier to handle by binding everything into a button that was not a submit, and if it passed the validation simply use a submit condition. This way I didn't need to worry about preventing default behavior and turning it back on again (which was where I was getting stuck). Since regular buttons have no default behavior, there was no need to be concerned about it submitting incorrectly.
The original function just needed to be simplified to:
var verifyValue = function() {
if($('#value_of_json_array').val().length != 0){
$('#value_of_json_array').prop("readonly", true);
$('#barcode-buttons').hide();
jQuery.getJSON('{{ path('query_to_get_array') }}?' +
$.param({barcode: $('#value_of_json_array').val()}))
.done(checkedValue);
}
};
$("#verify-value").click(verifyValue);
and then the check only needed to do this
var checkedValue = function(items) {
if(items.length == 0){
$('#form').submit()
}
else {
//error conditions
}
};

Controlling the submission

I'm trying to stop the submit if an error exists and go through the submission if no error exist.
This is just a section of the code. Regex works correctly, also the error texts were showing up too. The thing is that now I'm trying to control the submit proccess and due to an error (console is not showing up anything) the error text is not showing up and the submission is just going through even if an input error exists.
There is a mistake that I cannot figure out (No jquery please)
var sub = document.querySelector("#register input[type='submit']");//the submit botton
var err_text_1 = "First name must be filled out!";
sub.onsubmit = function(){
if (first_name == null || first_name == "") {
err_holder_1.innerHTML = err_text_1;
return false;
}
else {
err_holder_1.style.display = "none";
}
}
To prevent submit add event in the function and return false like so:
sub.onsubmit = function (event) {
// Will prevent submit
event.preventDefault();
return false;
};
Also select the form you are submitting not the button itself. So:
var sub = document.getElementById('ActionForm');
Hope this helps.
You need to select the form like
var sub = document.querySelector("#register");//If register is your form id Not input[type='submit']

How to prevent form submission during client side validation using infragistics control?

I have an infragistics webimagebutton with clientside click event
<igtxt:webimagebutton id="btnOwnerSave" runat="server" cssclass="bodytext" text="Save"
usebrowserdefaults="False">
<clientsideevents click="confirm_ssn"></clientsideevents>
</igtxt:webimagebutton>
I have a function that handles that event. This function displays confirmation dialog.
Now, when I click "CANCEL" button, postback happens. I do not want execution go back to the server. I just need it to stop as soon as user clicks "CANCEL", just as it can be done with regular javascript: return functionName()
This is my function:
function confirm_ssn()
{
var butPress;
var strMessage;
strMessage = "";
if (ss# is not valid)
{
strMessage = "There is a SSN starting with 9 \nClick OK to proceed, click Cancel to make change ";
butPress = confirm(strMessage);
if (butPress)
{
do something;
}
else
{
stop submitting the form;
return;
}
}
confirm_own_percentage();
return;
}
function confirm_own_percentage()
{
var percentageOwned = 0;
var ownerper = document.getElementById("txtOwnerPercentageOwned").value;
var secondownerper = document.getElementById("txtSecondOwnerPercentageOwned").value;
var butPress;
var strMessage;
if(!isNaN(ownerper))
{
percentageOwned = percentageOwned + parseInt(ownerper);
if(!isNaN(secondownerper))
{
percentageOwned = percentageOwned + parseInt(secondownerper);
}
}
if(percentageOwned < 50)
{
strMessage = "The % Equity Ownership is not equal or greater than 50%\nClick OK to proceed, click cancel to make change "
butPress = confirm(strMessage);
if (butPress)
{
do something;
}
else
{
stop submitting the form;
}
}
}
What can be done to achieve that?
Thank's
I found an answer to this question. Hole it will be helpful to someone in the future.
Basically, when using Infragistics's clientsideevent, this event receives references to an object it is used on and an event to be fired, for example, in my case, I just need to add these references in my parameter list:
function confirm_ssn(oButton, oEvent)
Then, in order to prevent form submission I need to use oEvent.cancel = true when I click "CANCEL" button on a confirmation dialog.
This will do the trick.
Hope it will help someone

disabling submit button till input fields are validated

i have disabled the submit button in my guestbook. it has 2 fields[name(textbox)&comment(textarea)].it has 2 other fields ID(primary key) and date.the function is:
function Frmvalidate() {
var nmchk=document.forms["guestform1"]["name"].value;
var cmntchk=document.forms["guestform1"]["comment"].value;
if (nmchk.length==0)
{
var namep = document.getElementById("namep");
namep.innerHTML="name must be filled out";
return false;
}
else if (cmntchk.length==0)
{
var cmntp = document.getElementById("cmntp");
cmntp.innerHTML="comment must be filled out";
return false;
}
else
{
document.getElementById("sbmt").disabled=false;
return true;
}
}
i have called the function in places: body tag's onload,button tag's onclick. still its not working and blank entries are being stored in my database.
You dont need to disable the submit button
you gain noting from it. ( alerting the user , running another script etc...)
instead -- The submit button should stop its regular behaviour by this code :
<input type="submit" onclick="return Frmvalidate();"/>
meaning :
when you press the button , it will execute the function yielding True or False and if it's True (only) it will continue to the server.

Categories

Resources