joining two javascript code as one single code separators - javascript

I need to create a re-useable function. The following script should prevent form submit and show a div alert. This version does not prevent form submit
<script type="text/javascript">
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
$(function() {
$('form#vendiendo').submit(function(e) {
if (Number($("#venta").val()) <
Number($("#costo").val())) {
$("#warnings").show();
//here start the new code I added
if (Number($("#cantidad").val()) >
Number($("#stock").val())) {
$("#warnings2").show();
//here ends the new code I added
return false;
}
});
});
</script>

If you want to stop the form from submitting in the case of an error, this should do.
<script type="text/javascript">
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
$(function() {
$('form#vendiendo').submit(function(e) {
if(Number($("#venta").val()) < Number($("#costo").val())) {
$("#warnings").show();
// You're still in the first if() statement. Is that what you want?
if (Number($("#cantidad").val()) > Number($("#stock").val())) {
// At this point, both checks have failed. We want to stop the
// default behavior.
e.preventDefault();
e.stopPropagation();
// And tell the user why we failed.
$("#warnings2").show();
return false;
}
});
});
</script>

Related

issues with the javascript addlistener submit functionality

I have the following code where i am blocking the code to stop its processing if the error happens
var objEditForm = document.getElementById("EditForm");
objEditForm.addEventListener("submit", function(e){
var error = 0;
$("##cell,##fax").on("invalid", function() {
let error = 1;
if($(this).val() == '') {
$(this).focus();
}
});
at the bottom i have this
if(error == 1) {
e.preventDefault();
}
and defined the var error = 0; at the top, it just goes inside that jquery code and does nothing, it alerts me 0 and then submits the form.
any idea what i am doing wrong here
i am sorry i was wrong .. thats write you did mistake in write selector in jquery
if "cell,fax" is elements id then its used wrongly in jquery..
it should be like "#cell" "#fax"..
it would be nice if you use jquery its pretty easy.apply even on your submit button i assum your button id is submit ok.
$("#submit").click(function(e)){
e.preventDefault();
var error = 0;
$("#cell,#fax").on("invalid", function() {
let error = 1;
if($(this).val() == '') {
$(this).focus();
}
});
but i am still not getting your cell and fax doing

Get Value Of File Input for Validation

I've been using JQuery validation for all of my forms on my website but I've just started on an upload script for image files and it's not validating correctly. Here is the code that I have:
$(document).ready(function()
{
var avatarok = 0;
//Post Avatar
$('#avatar').blur(function()
{
var avatar=$("#avatar").val();
if(avatar.length < 1){
avatarok = 0;
}
else{
avatarok = 1;
}
});
// Submit button action
$('#avatarButton').click(function()
{
if(avatarok == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
});
When I click on the button (avatarButton) it always shows the error class, even if a file has been selected. Any theories?
check the below solution and blur condition not executing so that u are getting same message
// Submit button action
$('#avatarButton').click(function()
{
var avatar=$("#avatar").val();
if(avatar == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
and remove your blur function no use

"Merge" LiveValidation with Jquery on a form

This is part of my jquery function that validades a form i have on my website:
/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateStep(step){
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
hasError = true;
$this.css('background-color','#FFEDEF');
}
else
$this.css('background-color','#A8FC9C'); /* Campo preenchido */
});
var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError){
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
/*
if there are errors don't allow the user to submit
*/
$('#enviar_candidatura').bind('click',function(){
var preenchimentoForm=true;
if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(preenchimentoForm);
//return false;
}
else{
dadosFormularios(preenchimentoForm);
}
});
});
However, i'm using too LiveValidation (http://livevalidation.com/) to validade fields client-side. Obiously, if the part validated by jquery is Ok, doesn't matter if there's errors on the LiveValidation part because the form is submitted.
So, what i want is to add an if clause or something like that inside this jquery code to verify if there are LV_invalid_fields. If 'yes' then block form from submitting like it's done with the jquery validation part, but i don't know how to do it neither where is the right place in the code above to put this verification. I would appreciate some help. Thanks!
//... live validation codes here
$("#myform").submit( function (event) ) {
event.preventDefault();
if ($(".LV_invalid").length > 0) {
//do not submit
}
else {
//do form submission here
}
}
First, you have to change the binding on the click to a binding on the submit action on the form.
And your function must return false on the submit action to stop the submitting action.
So, change your code like this :
$('#formElem').submit( function (event) ) {
var preenchimentoForm = true;
if ($('#formElem').data('errors')){
preenchimentoForm = false;
}
return preenchimentoForm;
}
You can read some explications about unobtrusive javascript here.
There is an option in the LiveValidation library which is not explained in the documentation http://livevalidation.com/documentation
To prevent LiveValidation's submission while still keeping its validation events, you may use the "afterValidation" option.
Example:
var prevent = function (e) {
e.preventDefault();
};
var yourValidation = new LiveValidation(
"inputID", {
//Your other options
afterValidation: prevent
}
);
yourValidation.add( Validate.Presence, { your options } );

JQuery Check if input is empty not checking onload?

I am using this code to check if an inputbox is empty or not and it works fine but it only checks check a key is press not when the page loads.
It's does what it should but I also want it to check the status when the page loads.
Here is the current code:
$('#myID').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
Try the following:
$(function() {
var element = $('#myID');
var toggleClasses = function() {
if (element.val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
};
element.on('keyup keydown keypress change paste', function() {
toggleClasses(); // Still toggles the classes on any of the above events
});
toggleClasses(); // and also on document ready
});
The simplest way to do is trigger any of the keyup,keydown etc event on page load. It will then automatically call your specific handler
$(document).ready(function(){
$("#myID").trigger('keyup');
});
try checking the value on a doc ready:
$(function() {
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
EDIT: just as an update to this answer, a nicer approach might be to use toggle class, set up in doc ready then trigger the event to run on page load.
function check() {
var $status = $('#status');
if ($(this).val()) {
$status.toggleClass('required_ok').toggleClass('ok');
} else {
$status.toggleClass('required_ok').toggleClass('not_ok');
}
}
$(function () {
$('#myID').on('keyup keydown keypress change paste', check);
$('#myID').trigger('change');
});
Well then why dont just check the field after the page is loaded?
$(document).ready(function(){
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
$(document).ready(function(){
var checkVal = $("myID").val();
if(checkVal==''){
$('#status').removeClass('required_ok').addClass('ok');
}
else{
$('#status').addClass('required_ok').removeClass('not_ok');
}
});

How to show <tr> tag on clicking button and prevent page refresh

My Requirement is to hide a tag initially, if user clicks forwardbutton without checking any radio or checkbutton we have show the tag and have to prevent page refresh. But it is permanently not submitting on click, Plese someone help me.
$(document).ready(function()
{
var y=$('input').filter(':checked').length;
alert(y);
if(y == 0 )
{
$('#Q1_7_label').parents('TR').hide();
}
$('#forwardbutton').live('click',function(event)
{
var x=$('input').filter(':checked').length;
if(x==0)
{
$('#Q1_7_label').parents('TR').show();
return false;
}
});
});
$('#forwardbutton').live('click',function(event)
{
var x=$('input').filter(':checked').length;
if(x==0)
{
$('#Q1_7_label').parents('TR').show();
return false;
}
return true;
});
Just add return true at the end of the function
Try to replace
return false;
with
event.preventDefault();

Categories

Resources