Javascript form validation with Jquery decoration - javascript

Please excuse my lack of javascript seasoning. I currently have two parts to my validation:
1. functions that apply css decoration to the input fields and makes the div that contains the error message visible
2. a function that aggregates the above functions and is called in the form ie, onSubmit="(return validate();)"
I wish to fix two things:
1. Refactor code so as to make it smaller
2. FIXED with code update. Apply selector text decoration to all empty fields. Currently, the decoration is applied to the first empty field then once a text value is entered, it hits the next field. Every empty field should be validated and show proper decoration.
/** VALIDATION DECORATION **/
function validateAccountNameRequired(textInputId, textInputLabelName) {
var valid = true;
if (!$('input#accountName').val()) {
$('input#accountName').addClass('inputError');
$('ul#accountNameList').find('div.error').attr('style', '');
valid = false;
} else if ($('input#accountName').val()) {
$('input#accountName').removeClass('inputError');
$('ul#accountNameList').find('div.error').hide();
}
return valid;
}
function validateAccountBusOrgIDRequired(textInputId, textInputLabelName) {
var valid = true;
if (!$('input#accountBusOrgID').val()) {
$('input#accountBusOrgID').addClass('inputError');
$('ul#busOrgList').find('div.error').attr('style', '');
valid = false;
} else if ($('input#accountBusOrgID').val()) {
$('input#accountBusOrgID').removeClass('inputError');
$('ul#busOrgList').find('div.error').hide();
}
return valid;
} /** VALIDATORS **/
function validate() {
valid = validateAccountNameRequired('accountName', 'Account Name');
valid1 = validateAccountBusOrgIDRequired('accountBusOrgID', 'Account Bus Org ID');
return valid && valid1;
}

I resolved my own issue. Hopefully someone else can benefit:
Validates all fields at once
Refactored for better cohesion, just load values in function validate() and reuse one function validateTextRequired():
function validateTextRequired( textInputId, errorListId)
{
var valid = true;
if( !$('input' + '#' + textInputId).val())
{
$('ul' + '#' + errorListId).find('label').addClass('error');
$('input' + '#' + textInputId).addClass('inputError');
$('ul' + '#' + errorListId).find('div.error').attr('style','');
valid = false;
} else if ($('input#' + textInputId).val()) {
$('ul' + '#' + errorListId).find('label').removeClass('error');
$('input' + '#' + textInputId).removeClass('inputError');
$('u' + 'l#' + errorListId).find('div.error').hide();
}
return valid;
}
function validate()
{
valid = validateTextRequired( 'accountName', 'accountNameList');
valid1 = validateTextRequired( 'accountBusOrgID', 'busOrgList');
valid2 = validateTextRequired( 'acctMgr', 'accountMgrList');
}

Related

List.js - filtering by an attribute with more than 1 key/value/answer

I'm trying to filter a List.js list by a data-attribute where the result has multiple answers:
<div data-colors="red, blue, green">Item Name</div>
When I try the following it wont search through each item:
$('.filter').on('click',function(){
var $q = $(this).attr('data-colors');
if($(this).hasClass('active')){
myList.filter();
$('.filter').removeClass('active');
} else {
myList.filter(function(item) {
if (item.values().colors == $q) {
return true;
} else {
return false;
}
});
$('.filter').removeClass('active');
$(this).addClass('active');
}
});
If I try it when there is only one result, then it works fine:
<div data-colors="red">Item Name</div>
I have tried various options to filter through each item, but nothing seems to work.
Any ideas?
I just did this analysis for a customer's project. We wanted a simple checkbox input system. The dilemma was individual elements within the Unordered list could have multiple roles (data-colors). I chose a single binary value to represent this. The filter used a simple Bitwise AND function. This worked well.
Complete Code is here.
Demo, via CodeSandBox is here. Be sure to look at console logs to understand the filtering transactions.
Key functions are here:
var teamKey = 16 + 8 + 4 + 2 + 1;
function OnChangeCheckbox(checkbox, listObj) {
if (checkbox.checked) {
console.log("The check box is checked. " + checkbox.value);
teamKey += parseInt(checkbox.value, 10);
} else {
console.log("The check box is not checked.");
// remove value from teamArray
teamKey -= parseInt(checkbox.value, 10);
}
console.log("teamKey: " + dec2bin(teamKey));
listObj.filter(filterList);
}
function filterList(item) {
console.log("indiv value: ", dec2bin(item.values().teams), " teamKey: ", dec2bin(teamKey) )
console.log( " Bitwise And: ", dec2bin(item.values().teams & teamKey));
if (item.values().teams & teamKey) { // the magic is here
console.log(" pass: ", item.values().teams & teamKey);
return true;
} else {
console.log(" fail: ", item.values().teams & teamKey);
return false;
}
}
The list element <div class="teams">XX</div> would be hidden via CSS display: none; in use.

javascript function to prevent user from changing the value of a specific column

Hope you're doing well
I'm new to JavaScript and I need your help to complete the code below.
I've written a JS code as you can see below :
$("#input_KindCode").change(function () {
if ($(this).val() == 1) {
RunSql("Select DateKey From ProjectExecution.Contractinfo WHERE PlanCode = " + $("#input_PlanCode").val() + " AND ProjectCode = '" + $("#input_ProjectCode").val() + "' AND ContractCode = '" + $("#input_ContractCode").val() + "' AND KindCode = 1 ", function (data) {
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
/////// THIS PART///////
} else {
$("#input_DateKey").val('');
EnableCol("DateKey");
}
});
}
else {
$("#input_DateKey")[0].value = '';
EnableCol("DateKey");
};});
In the 'RunSql' part of the code , I'm checking whether the 'datekey' column has value if true the value will show up in the field otherwise the user must enter the value for the column.
The problem is I want to add something to the code . I want to show the value if it exists AND I want to disable the column so that the user can not change the value . I can not use the function 'disable column' cause it does not work in my case are there any other functions ??
so I want a function to prevent user from changing the value of the column if it is being shown on the field. the function must be written in the 'This part' part of the code
Thanks in advance
You can disable this input field using jquery. To perform this you need to add one line.
Code:
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
$("#input_DateKey").prop('disabled',true);
} else {
$("#input_DateKey").val('');
$("#input_DateKey").prop('disabled',false);
EnableCol("DateKey");
}

Prevent Default not working, not sure why

I'm supposed to press enter to submit the form
my code doesnt work on this FIDDLE but it works on this one FIDDLE2.
I'm not really sure why and would like to see if anyone knows why. The code is exactly the same
var i = 0;
var allowed = /^[a-zA-Z0-9]+$/;
$('#form').submit(function(e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})
You have not included jQuery in the first fiddle, and that is why $ can not be resolved or defined error is there.
Second fiddle does includes jQuery and it is working as expected.
It is showing $ is not defined. It is means you are not including jQuery in your project.
add jQuery in your code. working fiddle here
Add
$('#form').submit(function(e){
e.preventDefault(); // Saves from Reloading of page
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if(!allowed.test(input)){
alert("Name can have only letters and numbers.\n\n Names Already Submitted: "+ ar.join(" , "));
return false;
}else{
ar[i]= input;
alert("Your name was successfully submitted\n\n Names Already Submitted: "+ ar.join(" , ") );
i = i+1;
return false;
}
});
try the below code
When the input is not matching your regex, then validation will occurs and page will get not submit.
use preventDefault in if (!allowed.test(input)) {
$('#form').submit(function (e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
e.preventDefault();
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})

Add/Remove value to input on click

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

Data.gui.js clear text with confirm box

dat.gui.js
I am trying to use the text input in DAT.GUI.js, when I click the input box, the text input box should be clear if there has a default value. After finished, it will come out a confirm box(Message Box) to inform the user their input message.
Right now, My code is like this, but if I choose the Cancel it can not clear the input text. If the default text is not empty, I still need to delete the world use Backspace And also I do not want the default name "Close Controls", can I delete this?
var params = {
text:""
};
var gui = new dat.GUI();
gui.add(params, 'text').name('ID:').onFinishChange(function (value) {
if (confirm('Is" '+ value + ' "id?') === true) {
workerId = value;
} else {
value = "";// I also tried params.text = ""; but still can not clear the input box
}
});
Any suggestion is appreciated, thanks!
Solved
gui.add(params, 'text').name('Your Worker ID:').listen().onFinishChange(function (value) {
if (confirm('Is" '+ value + ' "your worker id?') === true) {
workerId = value;
} else {
params.text="";
}
});
gui.add(params, 'text').name('Your Worker ID:').listen().onFinishChange(function (value) {
if (confirm('Is" '+ value + ' "your worker id?') === true) {
workerId = value;
} else {
params.text="";
}
});

Categories

Resources