jQuery submit() - form is still sent - javascript

I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!

the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.

$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length

Related

Fortify Scan - Race condition in jquery.validate

Fortify SCA flagged this line of code as a vulnerability, with the following warning:
The call to on() in jquery.validate.js on sets a callback that could lead to a race condition
https://github.com/jquery-validation/jquery-validation/blob/98fbc5f4287b9e580be6c1404094e9ae31b4abb2/src/core.js#L46
However based on my understanding, I don't see how is it setting a callback that might induce a race condition. Isn't it only listening for the "submit.validate" event?
How do I resolve this? Is this a vulnerability? I checked the CVE and security advisories in the github repo and I see no mention of it.
this.on("submit.validate", function(event) {
if (validator.settings.debug) {
// Prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden, result;
// Insert a hidden input as a replacement for the missing submit button
// The hidden input is inserted in two cases:
// - A user defined a `submitHandler`
// - There was a pending request due to `remote` method and `stopRequest()`
// was called to submit the form in case it's valid
if (validator.submitButton && (validator.settings.submitHandler || validator.formSubmitted)) {
hidden = $("<input type='hidden'/>")
.attr("name", validator.submitButton.name)
.val($(validator.submitButton).val())
.appendTo(validator.currentForm);
}
if (validator.settings.submitHandler) {
result = validator.settings.submitHandler.call(validator, validator.currentForm, event);
if (hidden) {
// And clean up afterwards; thanks to no-block-scope, hidden can be referenced
hidden.remove();
}
if (result !== undefined) {
return result;
}
return false;
}
return true;
}
// Prevent submit for invalid forms or custom submit handlers
if (validator.cancelSubmit) {
validator.cancelSubmit = false;
return handle();
}
if (validator.form()) {
if (validator.pendingRequest) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
});

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

Check if input field is empty on fields with jQuery

I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.

jQuery - trying to do a function inside an if statement

I'm trying to add some validation to a form. I have a jQuery function that is doing exactly what I want:
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
However, I want to change it so that this function only runs if a radio button elsewhere on the page is selected. So I tried this:
if (jQuery('#top').checked) {
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
}
That doesn't work - the function doesn't get called even if #top is checked. Can anyone explain why? I'm used to PHP, and JavaScript often throws curveballs at me.
What does firebug or Chrome console tell you? You could try something like this:
$('#top').is(':checked')
as in (thanks RET):
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
}
return false;
});
try
$('#top').is(':checked')
but the function submit only binds the function and calls it every time submit is clicked.
so you must put the checked check in the submit function
jQuery('#post').submit(function() {
if(!$('top').is(':checked')){ return };
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
});
Yeah, that logic won't quite do what you're hoping for. Try something like:
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
// all your existing code
I could be wrong, but I don't think the answer given by #greener is going to work, because that will only declare the submit function if #top is checked at page create time.

Stop redirect in JavaScript

I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit

Categories

Resources