Creating jQuery global variables for input form validation - javascript

I have what I believe to be a simple question, but I'm stuck:
I am trying to validate a credit card number in an input field.
I have a switch statement which picks up the type of credit card, and executes a validation function depending on the card detected.
The problem is, I'm struggling to insert a variable within my card validation function which represents the real-time card number (when the document loads, the field is empty).
Here's the HTML:
<form name="cardDetailsFrom">
<label>Enter Card Number</label>
<input type="text" id="cardNumber" name="cardNumber" />
</form>
Here's my jQuery:
$("#cardNumber").keyup(function(){
var cardNumber = $(this).val();
});
function validateAmericanExpress(){
if(cardNumber==//Rest of code doesn't work because can't pick up the local variable
};
Any help would be greatly appreciated by a jQuery newbie. I'm trying to avoid using the standard plugins though. Thanks!

This isn't jQuery specific, its just basic Javascript function calling.
$('#cardNumber').on('keyup',function(){
validateAmericanExpress(this.value);
});
function validateAmericanExpress(cardNumber){
if(cardNumber === // whatever, now the if logic will work
}
Basically, you are calling the function with the value on each keyup, and passing the value into the function as cardNumber to be used within that function.
This is better than using a large-scope variable because it doesn't require allocation of cache from the browser, increasing efficiency and speed. More importantly, it helps avoid possible collisions (multiple items setting the global variable in conflict) and makes code much more readable and easier to maintain.
Efficient use of possible returns
You can even make the code more appropriately-located as such:
$('#cardNumber').on('keyup',function(){
if(validateAmericanExpress(this.value)){ // this checks if the call returned true
// happy times
} else {
// show error message that says invalid
}
});
function validateAmericanExpress(cardNumber){
if(cardNumber === 'whatever'){
return true;
} else {
return false;
}
}
Or even better, use ternary!
$('#cardNumber').on('keyup',function(){
validateAmericanExpress(this.value) ? alert('correct') : alert('error');
});
function validateAmericanExpress(cardNumber){
cardNumber === 'whatever' ? return true : return false;
}
Super efficiency status! If you want to learn more about ternary / conditional operators, check out this reference.
Make function more extensible
Lastly, your cardnumber validator is probably just checking that its a specific number sequence right? You can probably do it without a function call:
$('#cardNumber').on('keyup',function(){
var regex = '/^3[47][0-9]{13}$/';
regex.test(this.value) ? alert('correct') : alert('error');
});
That is for testing for AmEx. If you are testing a variety of credit cards, you can use the function with a parameter, and make it crazy generic!
$('#cardNumber').on('keyup',function(){
validateCreditCard(this.value),'amex') ? alert('correct') : alert('error');
});
function validateCreditCard(cardNumber,type){
var regex;
switch(type){
case 'amex':
regex = '/^3[47][0-9]{13}$/';
break;
case 'visa':
regex = '/^4[0-9]{12}(?:[0-9]{3})?$/';
break;
case 'mastercard':
regex = '/^5[1-5][0-9]{14}$/';
break;
default:
regex = '/d{16,17}$/'; // just checking it is all numeric and appropriate length
}
return regex.test(cardNumber);
}
This will allow you to test all credit cards unilaterally, especially if instead of passing a string like 'amex' you use the value of a radio button selection. If you want more information about the regex strings for all the cards, check out this reference.

using a var inside a scope limits it to that scope
use PlantTheIdea's answer or just remove the var and make a new var cardNumer; outside

Related

Not repeating selectors in a conditional statement with JavaScript/jQuery

I have a small app with one form and one input field. When a user submits this form, I first want to see if the value only contains letters. If all is good, I want to pass the value on to a function.
Here's what I have:
$('form').on('submit', function(e) {
if ($('input').val().match(/^[a-zA-Z]+$/)) {
someFunction($('input').val());
} else {
// Error message or something else here
}
e.preventDefault();
});
I don't like writing $('input').val() twice (once in the conditional statement, and again if it holds true). Using this wouldn't work, since it's within a conditional statement and not some sort of function... Is there a way to not repeat code in this scenario?
Perhaps setting $('input').val() to a variable would be best?
Thanks!
Just do this:
var inputValue = $('input').val();
Bit old but I found this helpful : Not repeating selectors
var myvar = $('input');
As well as the clear discription :
basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Get a return value from arbitrary eval'd code

I have a requirement that the user can provide arbitrary statements which can be stored in a function and called later to get a return value. A simple example of this is that userInput might be
var x = 10;
x;
I would store this via
var callback = function() {
return eval(userInput);
}
and then running callback() returns 10 as expected.
However, I also need to support the case with an explicit return statement, ie userInput might be
var x = 10;
return x;
In this case the eval method above will fail with SyntaxError: return not in function. Instead I could store callback as
var callback = new Function(userInput);
My issue is that I would like to combine these two approaches according the rule 'get explicit return value otherwise get the result of the last executed statement'. In particular this can't be done with analysis of the code at callback creation time as the user could potentially do something odd like
if(envVar < 10)
return a;
b * 0.5;
which combines both.
Any thoughts on how to structure the creation of the callback function to accommodate these possible inputs? Unfortunately it is not possible to enforce one style or the other on the user.
UPDATE to answer some of the comments below.
One solution suggested is to search for a return token and choose between new Function and eval. This doesn't work for my last example, see http://jsfiddle.net/ZGb6z/2/ - out4 should be "no" but ends up being undefined as the last executed statement is not returned.
Another suggestion is to modify the user input to add an explicit return on the last line if one is not found. Unfortunately it's not possible to know which statement will be executed last. Consider
var x = 10;
switch(x) {
case 10:
100;
break;
default:
200;
break;
}
When called it should return 100, but it would take some serious analysis to determine where to put returns for arbitrary code.
Just use a try catch, manipulating the input will be very painful for you, and try catch can't really make your code any more obtuse at this point.
var failback = function () {
try {
return eval(userInput);
} catch (e) {
return Function(userInput);
}
};
What I would really suggest is investing in a parser, kind of like how Angular does it. That kind of thing would prevent your users from doing whatever the hell they want, introducing attack vectors, yadda, yadda, yadda.
Either manage your expectations or manage your user's expectations. eval and new Function() are not suitable for your requirements if you require mixed usage of explicit and non-explicit return statements in the same user-input. You will continue to find issues following either of these routes.
Simply searching for the word return is not sufficient either... var returning = true; or var a = 'return'; or /* return true */ true; will all throw false positives.
Managing your expectations: To do such a thing you require a form of lexer and parser, at which point you can do away with eval entirely and execute your own safe functions based on the parsed input. This is the best approach when execution of user input has to occur anyway as you can ensure that nothing gets executed you do not wish to permit. If you want to cover these sort of edge cases and permit strange user input then you must be prepared to increase the size and development time of your application. I have built a few applications executing user generated code and have always come to the conclusion this is the correct route to go down.
Managing your user's expectations: Provide a guide, tell them not to mix explicit returns with non-explicit returns, these are strange coding practices anyway. Better yet explicitly tell them to include or omit the return statement. There is no shame in asking your users to follow them, especially if it allows you to improve their experience elsewhere.
There I was thinking I'd only see problems like this at the code golf stack exchange :)
My solution is here: http://jsfiddle.net/hKq87/1
It essentially replaces the 'return' statement with an exception that has a special string prefixed to it. If we see that string, we know we are actually returning a value, and return it rather than re-raising the exception.
The reason I chose to throw an exception rather than replace the return statement with a function call was because it is hard to know where the JS code evaluated for the return really ends. It could be split across multiple lines, contain several special characters and may not even have the optional semi-colon at the end. So I concatenate a string to whatever the value being returned is and throw it, as the throw keyword doesn't require it's argument to be wrapped in parentheses.
In addition, throwing exceptions provides me a convenient way to immediately terminate execution of the code block, without halting other JS execution.
Here is the callback method:
var callback = function(userInput) {
var returned = undefined;
userInput = userInput.replace(/(^|[\(\\)[\]{};,\s])return(\s*[^\s;])?/gi, function(m, b, e){
return b + " throw '__RETURNED_VALUE'" +
(e !== undefined ? "+" + e : "");
});
try {
returned = eval(userInput);
} catch (e) {
if (e.indexOf("__RETURNED_VALUE") == 0) {
returned = e.substring("__RETURNED_VALUE".length) || undefined;
}
else {
throw e;
}
}
return returned;
}
The regex above accounts for variables that may end with the string "return", that we would not want to replace as it is not a return statement. It also allows for return statements within braces, without trailing semi-colons or at the very beginning/end.
One issue with the current method is that you can not use the (rare) comma operator in a return statement, or expect numerical values to be returned correctly. The last test case in the jsfiddle demonstrates this. An example from here:
//original
return 5 * 2 + 3, 22;
//modified
throw '__RETURNED_VALUE='+ 5 * 2 + 3, 22;
//apply * operator
throw '__RETURNED_VALUE='+ 10 + 3, 22;
//apply + operators
throw '__RETURNED_VALUE=103', 22;
//apply , operator
throw 22;
This problem can be avoided by completely eliminating the prefix '__RETURNED_VALUE=' and just replacing 'return' with 'throw'. However, this means that the code provided must run without throwing exceptions, which I thought to be a harder constraint than just crafting return statements to be simple (avoiding comma operators, non-parenthesized arithmetic, etc.). In addition, if a user ever creates a return statement that we can't handle with the current code, we conveniently throw an exception for it so it easily comes to our attention.
jsFiddle Demo
Lets assume your user can be a little smarter than the average bear. We are going to ask them to specifically provide an initial value and then a callback with an expression for that value.
The main benefit of doing this is that you avoid eval, and actually have a nice implementation that is re-usable as opposed to being subject to later refactoring.
This way also provides a separation of where the input comes from and where the examination comes from. Although the provided example only shows integer input, really it could be another call with absolutely no knowledge of the value aside that it needs to conform to the callback logic.
function expression(x,callback){
return callback(x);
}
out1.innerHTML = expression(8,function(x){
return x;
});
out2.innerHTML = expression(10,function(x){
return x;
});
out3.innerHTML = expression(10,function(x){
if(x === 10) return "yes"; "no";
});
out4.innerHTML = expression(8,function(x){
return x === 10 ? "yes" : "no";
});

Form handling and validation in pure JavaScript

My intention is to get your thoughts and criticism about the script below, as regards the algorithm's design, performance and cross-browser compatibility.
I have just started getting into JavaScript having missed out on its awesomeness for quite a while. My background and experience is in developing C/C++/PHP based RESTful backends.
In order to understand the language and the right way of using it, I decided to do something which I am sure has been done many times before. But learning to use a new language and paradigm often entails pain anyway.
This is my attempt to create a normal form processing and validation script/ function.
In order to reduce complexity and keep code simple/clean, I decided to use HTML5 Custom Data Attributes (data-*) to assign metadata for each element in the form:
Data-Required: True or False. If set to true, this parameter makes the form-field required and so it cannot be empty. A value set to false indicates that the field is optional. Default is false.>
Data-Type: Type of validation to be performed. Examples include 'email', 'password', 'numbers' or any other 'regexp'.
A fairy simple example of such a form would be:
<form action="postlistings" id="postlistings" enctype='multipart/form-data' method="post" class="postlistings">
<ul class="login-li">
<li>
<input class="title" name="title" type="title" id="title" data-required="true" data-type="title"></a>
</li>
<li>
<textarea name="body" id="elm1" class="elm1" name="elm1" data-type="body" data-required="true" >
</textarea>
</li>
<li>
<span class="nav-btn-question">Add Listing</span>
</li>
</ul>
</form>
Reminder: This is my first piece of JavaScript code.
The idea is to call Form while passing the form name to retrieve and validate all the field values in one loop for performance. The validation involves two steps as can be guessed from the Data-* attributes described above:
i. Check for required form fields.
In case the values fail to meet step 1 requirement, an error message from configuration is pulled for the specific form value. Thus, for all values that fail to meet this requirement, an array of error messages are collected and passed on to the View.
ii. Perform respective validations.
Validations are only performed if all the values passed step 1. Otherwise, they follow the same steps as indicated in 1 above.
function Form(){
var args = Array.prototype.slice.call(arguments),
formName = args[0],
callback = args.pop(),
userError = [{type: {}, param: {}}],
requiredDataParam = 'required',
typeDataParam = 'type',
form = document.forms[formName],
formLength = form.length || null,
formElement = {id: {}, name: {}, value: {}, required: {}, type: {}};
function getFormElements(){
var num = 0;
var emptyContent = false;
for (var i = 0; i < formLength; i += 1) {
var formField = form[i];
formElement.id[i] = inArray('id', formField) ? formField.id : null;
formElement.name[i] = inArray('name', formField) ? formField.name : null;
formElement.value[i] = inArray('value', formField) ? formField.value : null;
formElement.required[i] = getDataAttribute(formField, requiredDataParam);
formElement.type[i] = getDataAttribute(formField, typeDataParam);
if (formElement.required[i] === true){
if(!formElement.type[i]) {
error('Validation rule not defined!');
}
else if (!formElement.value[i]) {
userError[num++] = {'type': 'required', 'param': form[i]};
emptyContent = true;
}
}
if (emptyContent === false) {
// Perform validations only if no empty but required form values were found.
// This is so that we can collect all the empty
// inputs and their corresponding error messages.
}
}
if (userError) {
// Return empty form errors and their corresponding error messages.
}
return formElement;
};
// Removed the getFormParam function that was not used at all.
return {
getFormElements: getFormElements
}
};
Two outside functions that are used in the JS script above (from JQuery source):
var inArray = function(elem, array){
if (array.indexOf){
return array.indexOf(elem);
}
for (var i = 0, length = array.length; i < length; i++){
if (array[i] === elem){
return i;
}
}
return -1;
}
// This is a cross-platform way to retrieve HTML5 custom attributes.
// Source: JQuery
var getDataAttribute = function(elem, key, data) {
if (data === undefined && elem.nodeType === 1) {
data = elem.getAttribute("data-" + key);
if (typeof data === "string") {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!CheckType.isNaN ? parseFloat(data) :
CheckType.rbrace.test(data) ? parseJSON(data) :
data;
}
else {
data = undefined;
}
}
return data;
}
An example of Config Error messages can be set as follows:
var errorMsgs = {
ERROR_email: "Please enter a valid email address.",
ERROR_password: "Your password must be at least 6 characters long. Please try another",
ERROR_user_exists: "The requested email address already exists. Please try again."
};
As I post this for your review, please ignore any styling conventions that I might not have followed. My intention is to get your expert reviews on anything I should be doing different or could do better concerning the code itself, and the algorithm.
Besides the styling conventions, all criticism and questions are welcome.
First I'd like to clear up a common misconception. Forgive me if you already understand this clearly; maybe it will be helpful for someone else.
Learning and using jQuery or a similar library does not preclude or conflict with learning the JavaScript language. jQuery is simply a DOM manipulation library which takes away many of the pain points of using the DOM. There's plenty of room to learn and use JavaScript, the language, even if you use a library to abstract away some of the DOM details.
In fact, I would argue that using the DOM directly is likely to teach bad JavaScript coding habits, because the DOM is very much not a "JavaScript-ish" API. It was designed to work identically in JavaScript and Java and potentially other languages, and so it completely fails to make good use of the features of the JavaScript language.
Of course as you said, you're using this as a learning exercise; I just don't want you to fall into the trap that I've seen many people fall into of thinking, "I don't want to learn jQuery, because I want to learn JavaScript instead!" That's a false dichotomy: you have to learn JavaScript in either case, and using jQuery for the DOM doesn't interfere with that at all.
Now some details...
While it's OK to quote property names in an object literal and when you reference the properties, it's customary - and more readable - not to quote them when they are valid JavaScript names. e.g. in your formElement object
formElement = { id: {}, name: {}, value: {}, required: {}, type: {} };
(there was a missing semicolon at the end there too)
and where you use the names you can do:
formElement.id[i] = ...
formElement.name[i] = ...
etc.
Don't run your loops backwards unless the program logic requires it. It doesn't make the code faster except possibly in the case of an extremely tight loop, and it makes it unclear whether you're just prematurely optimizing or actually need the backwards loop.
Speaking of optimization, that loop has several inArray() calls. Since each of those loops through an array, that could be more of a performance impact than the outer loop. I imagine these arrays are probably pretty short? So performance wouldn't matter at all anyway, but this is something to think about in cases where you have longer arrays and objects. In some cases you can use an object with property names and values for a faster lookup - but I didn't look closely enough at what you're doing to suggest anything.
In any case, you're using inArray() wrong! But not your fault, that is a ridiculously named function in jQuery. The name clearly suggests a boolean return value, but the function returns the zero-based array index or -1 if the value is not found. I strongly recommend renaming this function as indexOf() to match the native Array method, or arrayIndex(), or some such.
That same loop has form[i] repeated numerous times. You could do this at the top of the loop:
var field = form[i];
and then use field throughout, e.g. field.id instead of form[i].id. This is generally faster, if it matters (which it probably doesn't here), but more importantly it's easier to read.
Do not use strict boolean comparisons like if( foo === true ) and if( bar === false) unless you really need to - and those cases are rare. The code sends a signal to the reader that there is something going on that's different from the usual boolean test. The only time these particular tests should be used is when you have a variable that may contain a boolean value or may contain some other type of value, and you need to distinguish which is which.
A good example of a case where you should use tests like these is an optional parameter that defaults to true:
// Do stuff unless 'really' is explicitly set to false, e.g.
// stuff(1) will do stuff with 1, but stuff(1,false) won't.
function stuff( value, really ) {
if( really === false ) {
// don't do stuff
}
else {
// do stuff
}
}
That specific example doesn't make a lot of sense, but it should give you the idea.
Similarly, an === true test could be used in a case where need to distinguish an actual boolean true value from some other "truthy" value. Indeed, it looks like this line is a valid case for that:
if (formElement['required'][i] === true){
given that if (formElement['required'][i] comes from the getDataAttribute() function which may return a boolean or other type.
If you are just testing for truthiness, though - and this should be most of the time - simply use if( foo ) or if( ! foo ). Or similarly in a conditional expression: foo ? x : y or !foo ? x : y.
The above was a long-winded way of saying that you should change this:
if (empty_content === false) {
to:
if (!empty_content) {
Your getFormParam() function goes to some work to convert an undefined result to null. There is usually no reason to do this. I don't see any place where that function is called, so I can't advise specifically, but in general you'd be testing for truthiness on something like this, so null and undefined would both be treated as false. Or in cases where you do need to distinguish null/undefined from other values (say, an explicit false), you can easily do it with != null or == null. This is one case where the "looser" comparison performed by == and != is very useful: both null and undefined evaluate the same with these operators.
You asked to ignore coding style, but one little suggestion here: You have a mix of camelCaseNames and names_with_underscores. In JavaScript, camelCaseNames are more idiomatic for function and variable names, with PascalCaseNames for constructor functions. Of course feel free to use underscores where they make more sense, for example if you're writing code that works with database columns in that format you may want your variable names to match the column names.
Hope that helps! Keep up the good work.
Update for your new code
I'm having a bit of trouble following the logic in the code, and I think I know part of the reason. It's a combination of naming conventions and inside-out objects.
First, the name formElement is really confusing. When I see element in JavaScript, I think of either a DOM element (HTMLElement) or an array element. I'm not sure if this formElement represents one or the other or neither.
So I look at the code to figure out what it's doing, and I see it has id:{}, name:{}, ... properties, but the code later treats each of those as an Array and not an Object:
formElement.id[i] = ...
formElement.name[i] = ...
formElement.value[i] = ...
formElement.required[i] = ...
formElement.type[i] = ...
(where i is an integer index)
If that code is right, those should be arrays instead: id:[], name:[], ....
But this is a red flag. When you see yourself creating parallel arrays in JavaScript, you're probably doing it wrong. In most cases you're better off replacing the parallel arrays with a single array of objects. Each of the objects in that array represents a single slice through all your parallel arrays, with a property for each of the previous arrays.
So, this object (where I've made the correction from {} to [] to match its current use):
formElement = { id: [], name: [], value: [], required: [], type: [] };
should be:
formInfo = [];
and then where you have the code that goes:
formElement.id[i] = ...;
formElement.name[i] = ...;
formElement.value[i] = ...;
formElement.required[i] = ...;
formElement.type[i] = ...;
It should be:
var info = {
id: ...,
name: ...,
value: ...,
required: ...,
type: ...
};
formInfo.push( info );
and adjust the rest of the code to suit. For example:
formElement.required[i]
would be:
formInfo[i].required
or even simpler since it's in the same function:
info.required
And note: I'm not saying info and formInfo are great names :-) they are just placeholders so you can think of a better name. The main idea is to create an array of objects instead of a set of parallel arrays.
One last thing and then I'm out of time for now.
That getDataAttribute() function is a complicated little piece of work. You don't need it! It would be simpler would just call the underlying function directly where you need it:
var info = {
...
required: formField.getAttribute('data-required') === 'true',
type: formField.getAttribute('data-type')
};
This also gives you full control of how the attributes are interpreted - as in the === 'true' test above. (This gives you a proper boolean value, so when you test the value later you don't have to use === true on it.)
On a stylistic note, yes, I did hard code the two 'data-xxxx' names right there, and I think that's a better and more clear way to do it.. Don't let your C experience throw you off here. There's no advantage to defining a string "constant" in this particular case, unless it's something that you want to make configurable, which this isn't.
Also, even if you do make a string constant, there's a minor advantage to having the complete 'data-whatever' string instead of just 'whatever'. The reason is that when somebody reads your HTML code, they may see a string in it and search the JS code for that string. But when they search for data-whatever they won't find it if the data- prefix is automagically prepended in the JS code.
Oh, I forgot one last thing. This code:
function Form(){
var args = Array.prototype.slice.call(arguments),
formName = args[0],
callback = args.pop(),
is working way too hard! Just do this instead:
function Form( formName, callback ) {
(and keep the var for the remaining variable declarations of course)
I cannot add comments yet so here is a little tip. I would separate the getFormElements() into smaller private functions. And I would add the errorMsgs to the Form function.
But for a first script in JavaScript, it is very impressive. This is actually the real reason I respond. I think it deserves more upvotes, and I would be very interested in a JS ninja responding to this question.
Good luck!

Check all values in an array are same

I have a webpage that has a textbox.
When the user enters information into it, it makes a AJAX call to see if the entry is valid, if not it disables a button.
They can also add up to 10 textboxes which is done via jQuery Templates. At the moment each textbox has a class of serial and when a serial textbox is blurred it does this check.
If they enter a invalid serial it will disable the button but if they add a new textbox and that is valid the button is now enabled which is wrong as there is one still invalid.
The only way I can think to do this is to add a 1 or 0 to an array for each textbox and once all elements in the array are 1 then enable the button. Is that a good approach, if not please explain a better one. If it is a good approach how do I check all values in a javascript array are the same?
Thanks
This sounds like a good approach. You can check for equal elements in a javascript array using this simple javascript function. You may paste this to a firebug console to check its functionality.
// check if all elements of my_array are equal, my_array needs to be an array
function check_for_equal_array_elements(my_array){
if (my_array.length == 1 || my_array.length == 0) {
return true;
}
for (i=0;i<my_array.length;i++){
if (i > 0 && my_array[i] != my_array[i-1]) {
return false;
}
}
return true;
}
//Example:
var my_array = [];
my_array.push(5);
my_array.push(5);
// will alert "true"
alert("all elements equal? "+check_for_equal_array_elements(my_array));
my_array.push(6);
// will alert "false"
alert("all elements equal? "+check_for_equal_array_elements(my_array));
I will assume you have a isValid(str) function that returns a boolean.
Since you're using jQuery, you can take advantage of jQuery's filter() function to easily check if any inputs are invalid whenever an input blurs:
$('.serial').live('blur', function () {
// Get an array of all invalid inputs
var invalids = $('.serial').filter(function () {
return !isValid($(this).val());
});
// Does the array contain anything?
$('#button').prop('disabled', invalids.length);
});
Demo: http://jsfiddle.net/3RNV6/
Similar concept, but for use with AJAX:
$('.serial').live('blur', function () {
var me = this;
$.ajax({
// ajax config
success: function (data) {
if (data === 'Y') $(me).addClass('valid');
// Get an array of all invalid inputs
var invalids = $('.serial').filter(function () {
return !$(this).hasClass('valid');
});
// Enable if none invalid
if (invalids.length === 0) $('#button').prop('disabled', false);
}
});
});
$('.serial').live('keypress', function () {
$('#button').prop('disabled', true);
$(this).removeClass('valid');
});
First of if you dynamically create n textboxes you should use live() or delegate() methods of jQuery to inform of new DOM elements added.
Secondly your approach is just fine but instead of an array you can set param of inputs with wrong text and then disable button if there are any elements with wrong text. I think it will be faster than looping though all textboxes all over.
I would use validation to achieve this.
http://docs.jquery.com/Plugins/Validation#Demos
If you can validate client-side great - either use one of the existing jQuery validation functions shown in the link above, or write your own.
If you must validate server side via ajax, then you could build this into a custom validation routine.
Then in the call that shows/hides the button - make a call to $('#formid).validate() - returns false if any validation fails.

Categories

Resources