Why does this jQuery input value checker not work? - javascript

I need to check all the inputs to see if they are filled, in which case the submit button would become pressable and the user can submit their data safely:
unfilled = false;
$('.add-field').keypress(function(){
$('.add-field').each(function(){
if($(this).val() === ''){
unfilled = true;
} else {
unfilled = false;
}
})
console.log(unfilled);
});
This code works, but it has a strange twist; as the last empty input gains a character, it still returns true. If an input gains another character, only then it will return false. I am confused by this, as I understand that the .each() function is fired after a character has been added and the value of the input has been updated. Consequently, I do not see why it does not register that value.

You should set unfilled to false before entering the loop (but INSIDE the keyup).
In the loop you should only set unfilled to true when a field is emty and not set it to false again, otherwise you'll only know if the last field is filled in.

You could use filter and use keyup event instead for del keys:
DEMO
$('.add-field').keyup(function () {
var unfilled = !! $('.add-field').filter(function () {
return $.trim(this.value) === ""
}).length;
console.log(unfilled);
});

Here === means it is matching exactly the data types:
if($(this).val() === ''){
Replace it with == :
if($(this).val() == ''){

As far as I know, this is an 'issue' when using the KeyPress-event, because the Browser's UI Thread did not update the input field's value yet. Therefore the value currently is still 'empty' and thus true is returned; you can either use the KeyUp-event or try something like this: JavaScript keypress event get end value of textarea

Related

jQuery - Simple validation for two inputs

I have two inputs: the first one is X - file upload. the second one is Y- an input for an URL.
So far I have a code that checks if Y is valid then remove the attribute required for X. otherwise I want the X to be required.
$(Y).blur(function(){
if ($(this).is(':valid') == true) {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false) {
$(X).attr('required');
}
});
for some reason this code works when the input Y is valid it removes the attribute. But let's say the user regrets and wants to leave Y blank, it doesn't return the required attribute for X.
Tried to keep the explanation as simple and clear as possible. If there is a misunderstanding I'll try to edit this question and make it clearer.
The easiest way is:
$(Y).blur(function(){
if ($(this).is(':valid') == true && $(this).val() != '') {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false || $(this).val() == '') {
$(X).attr('required');
}
});
In that case when user removes the content, required attribute will be returned back (dont forget to add trim function, I didnt use it in the sample).
I would recommend to capsulate this logic into validation functions. I also dont like blur event (usability is bad), I would recommend onchange event for field validation.

How To Check For Empty Fields In HTML Form With JavaScript

I'm checking a website registration form with JavaScript code and onchange listeners.
Empty fields/spaces need to be checked for first before checking for illegal characters, too long strings, etc.
I've read this.
But for a null string,
if (field.value ==="")
alert("Empty field!");
this will not generate the desired alert.
People at the end of the above thread suggested that recent browser versions might not accept such a statement.
So, how do I sort out empty/blank/ignored fields ?
EDIT 1
I've already tried
if (!field.value)
but it only provides an alert if the user has already typed some characters in the field and immediately deleted them before entering a blank field. It will not provide an alert just by clicking the mouse on it and then tabbing on to the next field. It looks like I may need to assign a null value to these form fields at the outset . . I am using implicit adding of the changeEvent listener, i.e. on seeing a value explicitly assigned to the onchange attribute of an element, it is activated without any addEventListener(..) statement.
Also,
if (field.value.length == 0)
does not seem to produce any alert.
EDIT 2
Sorted, I think.
I was using the JavaScript null field check as part of a field-by-field validation check on a web form.
I was using onchange as the event handler. This was wrong. What was needed here was onblur since in the case of a completely null field (i.e. a field on which nothing had been entered before tabbing away from it), no change has been effected -- and therefore no onchange event occurs that would trigger a JavaScript alert.
Thanks for your efforts.
I was stuck on this one across a couple of weeks and only sorted it with the help of some experimental programming by a more experienced guy at work here.
In this script you can see an alert of your variable value ( a console.log would be lees noisy :)
The use of === is for type check but in your example does not make sense as you are using an empty string
<script>
var field= {};
checkEquality(field);
field.value = "";
checkEquality(field);
function checkEquality(object){
alert(object.value);
if (object.value === "")
{
alert("===");
}
if(object.value == ""){
alert("==");
}
}
You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

How do I validate entry before input value is set?

I'm having a really strange problem. Here's my current Javascript:
jQuery('.highlightableTDCell input').keydown(function () {
var val = jQuery(this).val();
if (!GridView.prototype.validateStandardCellNumberFormat(val)) {
return false;
}
else return true;
});
When I use this, I can still get away with entering an illegal character, but no more than that. I'm really confused because I thought this would happen first.
Inside of the keydown event, the element.value has not yet been updated to account for the key that is currently being pressed. If you want to stop the key from hitting the input box, you need to interrogate the event.which and see if it is a key you want to allow or not.
The event is raised before the new content entered the input (letting you cancel the default behavior.)
You can use something like this, to get the new content:
$('.highlightableTDCell input').keypress(function(e){
var temp = this.value + String.fromCharCode(e.which)
return GridView.prototype.validateStandardCellNumberFormat(temp)
});
Note that it's not full proof. like when the user entered the new char in the middle of the input.
Validation should be done only on blur. With HTML5 it should be better, but not all browsers support it yet.
Tip: this.value == jQuery(this).val() There is no need to create jQuery object to get the value

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.

Use jquery to get an input's id and compare it against a static array of id's?

I am using jQuery to create a client-side validation function for a .NET form. Each form element has an id and several of the form elements are required fields.
In my validation script, I thought of creating an array of the id's of the 'not required' elements, then on every 'blur' event checking whether or not the current element ($(this)) is part of the array of elements not to check, but it doesn't seem to be checking against the list.
function validate(){
$('.form_wrapper input').blur(function(){
var isEmpty = $(this).val();
var isRequired = $(this).attr('id');
var notRequired = ['txtHomePhone','txtWorkPhone','txtMobile','txtStreetAddress','txtSuburb'];
if (isEmpty == "" && isRequired == notRequired){
// run conditional validation stuff
}
else {
// run other conditional validation stuff
}
});
}
The area I think I need help with is the if statement checking whether or not the current form element is part of the array of id's not to validate. I am also not really sure if it's actually an array I want/need to use in this situation?
Any help would be great,
Thanks,
Tim
not exactly sure here, but wouldn't you want to be doing
$.inArray(isRequired,notRequired) >= 0
instead of
isRequired == notRequired
EDIT
$.inArray() returns -1 if no match is found. Modified code to correctly show this behavior.

Categories

Resources