Validation best approach while looping fields - javascript

I have a save button handler inside which i check the employee name , skills and level for the employee which can be in multiple. I need the best possible way to do it as i am certain the way i do it looks really messy. Thanks
JS code:
$("#btnSave").click(function(){
var empName = $("#empName").val().trim(); // VALIDATE THIS
var skillArr = [];
var empObj = {};
if(empName != '')
return false;
$(".trSkillCls").each(function( index ) {
// VALIDATE FOR skill and level
if($(this).find('input[name=skill]').val().trim() == '' || $(this).find('select[name=ddlSkillLevel] option:selected').text().trim() == '')
return false;
skillObj = {
"skill" : $(this).find('input[name=skill]').val(),
"level" : $(this).find('select[name=ddlSkillLevel] option:selected').text()
};
skillArr.push(skillObj);
});
empObj = {
"empName" : $("#empName").val(),
"skillDetails" : skillArr
};
$.post( "indexBase.php",
$('#str').val(JSON.stringify(empObj)),
function(info){
var result = JSON.parse(info);
$( "#divEmpDetails" ).empty();
$("#divEmpDetails").append($("#tmplEmpDetails").render({data:result}));
// verify this callback for failures
});
$("#mainForm").submit( function() {
return false;
});
$('.trSkillCls').not(':first').remove();
$( "#reset" ).trigger( "click" );
});

Related

Prevent multiple Javascript execution for submit function

I am using the following code to allow users to submit content to an online board:
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
Unfortunately, if a user rapidly presses enter or rapidly clicks the send button, the code will execute multiple times and their message will be sent multiple times.
How can I modify my code to prevent this multiple execution?
A simple client-side fix would be to create a local variable that tracks whether or not anything has been submitted and have the function only execute if false.
var submitted = false;
$('form').submit(function(){
var form = $(this);
var name = form.find("input[name='name']").val();
var code = form.find("input[name='code']").val();
var content = form.find("input[name='content']").val();
if (name == '' || content == '')
return false;
if (submitted)
return false;
submitted = true;
$.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
$('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
$('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
form.find("input[name='content']").val('').focus();
});
return false;
});
A better solution would be to send a unique token for the transaction to the client and have the client send it along with the request.
You could have server-side coded to verify that the token has only been used once.
found this solution here
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});

TypeError: click called on object that does not implement interface HtmlElement

I've seen the other questions on this topics, but i can't spot the error in my code.
$('#submit_bulk').on('click',function(e){
var action = $('select[name="bulk_action"]'),
targets = $('table tr td:first-child :checkbox:checked');
if(action=='invalid' || targets.length == 0){
sk.alert('Nothing to do','warning');
return false;
}else{
$(this).html('Working....');
var fData = {
action: action,
mixtapes: '',
singles: ''
};
$.each(targets,function(i,v){
if($(this).data('type') == 'mixtape'){
fData.mixtapes += $(this).data('id')+',';
}else{
fData.singles += $(this).data('id')+',';
}
});
fData = $.param(fData);
console.log(fData); //i get no output here. is fData null?
$.post(window.location.origin+'/adminAPI/bulk_action',fData,function(data){
var data = JSON.parse(data);
if(data.error==0){
sk.alert('Your changes were saved','success');
//update view here.
}else{
sk.alert(data.message,'error');
}
});
$(this).html('go');
}
});
Word to the wise. make sure you are not passing a jQuery selector as a value into your form data.
the offending line was:
var action = $('select[name="bulk_action"]')
should have been:
var action = $('select[name="bulk_action"]').val()

Jquery Uncaught Error Syntax error, unrecognized expression: li/label

I want to insert a cookie notification bar. Now on a old Newsletter page I get a error like this:
Uncaught Error: Syntax error, unrecognized expression: li/label
the following code from the newsletter is
if( document.addEventListener ) document.addEventListener( 'DOMContentLoaded', cmxform, false );
function cmxform(){
// Hide forms
$( 'form.cmxform' ).hide().end();
// Processing
$( 'form.cmxform' ).find( 'li/label' ).not( '.nocmx' ).each( function( i ){
var labelContent = this.innerHTML;
var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
var labelSpan = document.createElement( 'span' );
labelSpan.style.display = 'block';
labelSpan.style.width = labelWidth;
labelSpan.innerHTML = labelContent;
this.style.display = '-moz-inline-box';
this.innerHTML = null;
this.appendChild( labelSpan );
} ).end();
// Show forms
$( 'form.cmxform' ).show().end();
}
//function to check empty fields
function isEmpty(strfield1, strfield2) {
strfield1 = document.forms.newsletter_subscribe.nome.value
strfield2 = document.forms.newsletter_subscribe.email.value
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ')
{
alert("Please insert your name!")
return false;
}
if (strfield2 == "" || strfield2 == null || strfield2.charAt(0) == ' ')
{
alert("Please insert a valid Email!")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms.newsletter_subscribe.email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1)
{
alert('Email not valid! Please retry!');
return false;
}
return true;
}
//function to check privacy
function Privacy()
{
if (document.forms.newsletter_subscribe.checkbox.checked==false)
{
alert('Please accept the privacy conditions!');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(){
if (isEmpty()){
if (isValidEmail()){
if (Privacy()) {
return true;
}
}
}
return false;
}
//**********************************************************************************************
//function to check empty fields unsubscribe form
function isEmptyEmail(strfield1) {
strfield1 = document.forms.newsletter_unsubscribe.email.value
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ')
{
alert("Please insert a valid Email!")
return false;
}
return true;
}
//function to check valid email address
function isValidEmailCancel(){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms.newsletter_unsubscribe.email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1)
{
alert('Email not valid! Please retry!');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check_unsubscribe(){
if (isEmptyEmail()){
if (isValidEmailCancel()){
return true;
}
}
return false;
}
When delete the new resource, that newsletter script is ok. But, when use the new jQuery resource get this failure.
If you want to concatenate more than one selector in jQuery find you are using the wrong syntax
$( 'form.cmxform' ).find( 'li/label' ).not( '.nocmx' ).each( function( i ){
should become:
$( 'form.cmxform' ).find( 'li, label' ).not( '.nocmx' ).each( function( i ){
and this means you are looking for any li OR label tag in the DOM scope you have selected ('form.cmxform')

using jquery addclass and removeclass in PHP

I' working on a PHP-Jquery-Ajax submit info form and I would like to use the addclass and removeclass jquery methods but I can't make it work as I want, so my question is: How do I have to fix the code below in order to add a css depending on the user input?
The addclass and removeclass are in the function verificaForm where I validate the input fields, in this case I only show you two fields validations but there are more... I also know that out there is a library(validate.js) that helps to validate the inputs from users but in this specific case I must have to sitck to this code.
here is my js code and thanks in advance:
$(document).ready(function () {
$('#ID_formulario').on('submit', function (e) {
e.preventDefault();
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
$('#result').html("<b>resolviendo peticion...</b>");
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
//...more code goes here ... it works fine ...
}
});
});
function validaForm(nombre, email) {
if ((nombre == '') || nombre.replace(/s+/, '') == '') {
alert("Favor especificar nombre");
nombre.addClass('hightlight');
return false;
} else {
else nombre.removeClass('hightlight');
}
if (nombre.length < 4) {
alert('El valor del campo es muy corto');
return false;
}
if ((email == '') || email.replace(/s+/, '') == '') {
alert("Favor especificar correo");
return false;
}
return true;
}
You should pass the element to the function, not the value. Then You can obtain the value within the function. Something like that:
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email))
....
function validaForm(nombre,email){
var nombre_value = nombre.val().trim();
var email_value = email.val().trim();
.......
So, you can add classes to a jQuery object and not to a value. Change things around like below.
Replace
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
With
if (validaForm($('input#ID_nombre'), $('input#ID_email'))) {
And modify your function as below.
function validaForm(nombre,email) {
var nombreVal = $.trim(nombre.val());
var emailVal = $.trim(email.val());
if ((nombreVal == '') || nombreVal.replace(/s+/, '') == '') {
..........
..........
}
And remove that extra else in here:
} else {
else nombre.removeClass('hightlight');
}
And change it to
} else {
nombre.removeClass('hightlight');
}

jquery and data-attr not working in ie8

This concerns a table where I show 5 rows at a time.
The follow code is working 100 percent perfect in firefox. But in ie8,
only the top row can be clicked for the editdiv to show. Whereas, in firefox
I can click on any of the five rows and the editdiv loads as expected.
Line in php file that calls the function:
echo "<td><a id=\"editjq\" href=\"#\" vid='".$vid."' t1='".$db->hscadd($t1)."' page='".$page."' flag='1')\"> [edit ] </a></td>";
The function:
$(document).ready(function() {
$('a#editjq').click(function() {
var petid = $(this).attr('vid');
var t1 = $(this).attr('t1');
var page = $(this).attr('page');
var flag = $(this).attr('flag');
$("#petdiv").hide();
$.post("edit_lookup.php", {
petid : petid,
t1 : t1,
page : page
}, function(data){
if (data.length>0){
$("#editdiv").html(data);
}
});
$(this).unbind();
return false;
});
});
Are you producing five rows which each have an anchor with the same id attribute? If so, that's your problem. It is syntactically illegal to have more than one element with the same id. Instead of id="editjq" use class="editjq" and $('a.editjq').click(...).
You could put this piece of jquery plugin code in your page script (just make sure that it comes after the jquery.min.js script tag);
(function($){
var store = {};
$.fn.extend({
collection : function(action, name, value) {
var $this = this;
var generate = function(){
return "COLLECTION" + parseInt((Math.random() * 100000), 16);
}
var item_id;
var methods = {
put: function(){
item_id = $this.attr("id");
if(store[item_id]){
store[item_id][name] = value;
} else {
while(store[item_id] && $(item_id).length > 0){
item_id = generate();
}
$this.attr("id", item_id);
store[item_id] = {};
store[item_id][name] = value;
}
return $this;
},
get: function(){
item_id = $this.attr("id");
if(store[item_id] && store[item_id][name]){
return store[item_id][name];
}
else{
return null;
}
},
remove: function(){
item_id = $this.attr("id");
if(store[item_id]){
store[item_id][name] = null;
}
return $this;
}
}
if(methods[action]){
return methods[action]();
} else{
return alert(store.text.length);
}
return $this;
}
});
})(jQuery);
It can be used as follows:
store a data value
$(*selector*).collection("put", *DataName*, *DataValue*);
retreive a data value
var referencing_variable = $(*selector*).collection("get", *DataName*);
delete a data value
$(*selector*).collection("remove", *DataName*);
This is a cross browser solution. Though i have only tested it with Jquery 1.5.1

Categories