Conditional logic not working - javascript

This should be simple but I can't get it to work. I am attempting to check if the value of a hidden input is empty on focus of a textarea in the same form. I don't understand why this does not alert() my message when empty:
$("#postbody").focus(function() {
var inputLength = $("#topicCategory").val().length;
console.log(inputLength);// outputs 0
if( inputLength == 0 ) {// condition is true, but code does not run.
alert("Please select a category to post your question in.");
}
});
Am I missing something here?
I have also tried all sorts of other ways with no luck.

I tried your conditional statement and it does work.
Since you are expecting a zero, instead of using double equals to check against zero you can use the NOT operator since zero evaluates as falsy.
if (!inputLength) {// condition is true, but code does not run.
console.log("Please select a category to post your question in.");
}
Truthy and Falsy: When All is Not Equal in JavaScript

You are attaching onfocus handler function for the textarea postbody before it is created in DOM. You have to attach the handler function inside JQuery.ready() function which ensures the code inside it is executed after the DOM is ready.
$(document).ready(function(){
$("#postbody").focus(function () {
var inputLength = $("#topicCategory").val().length;
console.log(inputLength);// outputs 0
if( inputLength == 0 ) {// condition is true, but code does not run.
alert("Please select a category to post your question in.");
}
});
});

Related

Javascript stops when first if condition fails, need to move it to second condition

I have the following code in which I ask it to check if either one of 2 dataLayer values is "!= false" then run the rest of the code.
However, code breaks as soon as the first condition fails and does not move to check the second condition. So, how can I let both conditions be checked as one of them will always be available in dataLayer?
function init() {
if (dataLayer.condition[1] != false || dataLayer.condition[2] != false) {
Do something
}
}
Below is the screenshot of the error I get when the first condition values are missing on the page.
You can use optional chaining (?.) for this, if your execution context is expected to support it:
if (dataLayer?.condition[1] != false || dataLayer?.condition[2] != false) {
// Do something
}

Why does this jQuery input value checker not work?

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

Simplify this If statement so it doesn't duplicate code - Javascript

I have an If statement that runs within a 'for' loop to create markers for a Google map. Basically if a tick box is not ticked it runs the code all displays all markers, but if a checkbox is ticked then it checks for a 2nd parameter and only runs the code for the items that match this condition.
The code I have below works fine, but it means I have to use the same code in both parts of the if statement. Apart from building it into a function if there a better way of structuring the If statement to achieve this?
if(!FriendlyChecked){
//Code here
} else if(FriendlyChecked && Friendly == "Yes"){
//Same code here
}
If FriendlyChecked is false, the first condition is satisfied and the code will be executed.
Thus, if the second condition is reached, FriendlyChecked must be true, so you don't need to check it at all, you only need to check that Friendly == "Yes".
if(!FriendlyChecked || Friendly == "Yes"){
// code here
}
if( !FriendlyChecked || (FriendlyChecked && Friendly == "Yes") ) {
// your code
}
!FriendlyChecked || (FriendlyChecked && Friendly == "Yes") will check for either FriendlyChecked is false (not checked)
OR FriendlyChecked is true an value of Friendly is Yes
This will solve your problem
if((!FriendlyChecked) ||((FriendlyChecked)&&(Friendly == "Yes")){
//Code here
}

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