bootstrap-select is flashbacked,i used django and bootstrap [duplicate] - javascript

I have some JavaScript code that gives this error:
Uncaught TypeError: Cannot read property 'value' of undefined
Here is my code:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
What does this error mean?

Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

Try this, It always works, and you will get NO TypeError:
try{
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}catch(e){
if(e){
// If fails, Do something else
}
}

First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like
if (typeof document.getElementsByName("username")[0] != 'undefined')
Similarly for the other element password.

The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.

You can just create a function to check if the variable exists, else will return a default value :
function isSet(element, defaultVal){
if(typeof element != 'undefined'){
return element;
}
console.log('one missing element');
return defaultVal;
}
And use it in a variable check:
var variable = isSet(variable, 'Default value');

You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

Related

Cannot read property 'value' of null on simple var assignment: var goToThis = "";

I'm getting a javascript error Cannot read property 'value' of null on simple var assignment var goToThis = "";
// It is the second function that has the error.
function nextFocus(tLast) {
var goToThis = "";
var val = 0;
if(tLast === 'activity') {
if(document.getElementById('[Slip]Note').value === "") {
document.getElementById('[Slip]Note').value = document.getElementById('[Slip]Activity').value;
}
}
if((tLast === 'activity') && (fLedes === true)){
document.getElementById('[Slip]Task No').focus();
} else if((tLast === 'activity') && (fLedes === false)){
goToThis = 'billableHrs';
} else if(tLast === 'expense'){
goToThis = 'priceAdjustment';
} else if((tLast === 'task') && (initialSlipType === 'time')){
goToThis = 'billableHrs';
} else if((tLast === 'task') && (initialSlipType === 'expense')){
goToThis = 'priceAdjustment';
}
if(goToThis === 'billableHrs') {
val = getReal(document.getElementById("[Slip]Billable Hrs"));
if(val === 0) {
document.getElementById("[Slip]Billable Hrs").value = '';
//alert('[Slip]Billable Hrs: '+val);
}
document.getElementById('[Slip]Billable Hrs').focus();
} else if (goToThis === 'priceAdjustment') {
val = getReal(document.getElementById("[Slip]Price Adjustment"));
if(val === 0) {
document.getElementById("[Slip]Price Adjustment").value = '';
//alert('[Slip]Price Adjustment: '+val);
}
document.getElementById('[Slip]Price Adjustment').focus();
}
}
This error was solved by correcting the spelling of an HTML element involved with this function call.
Safari pointed to the correct error line.
Chrome would not point to the correct error line.
Check opening and closing curly braces {} on all functions of the page. Sometimes {} mismatch ,also gives weird errors. Also try '' instead of "";

Assign a standard jQuery function to a variable

How can I assign these functions submit() and click() to a variable. So that I can use them in an if statement like this:
function sendToCheckout() {
$(document).ajaxComplete(function(){
if($("form[action='/cart']").length == 1){
var x = submit();
}
else {
var x = click();
}
$("form[action='/cart']").off().x(function(event){
event.preventDefault(event);
var amountToSend = sessionStorage.getItem('amountToSend');
if(amountToSend != null && amountToSend != "0"){
sendData();
}
else{
window.location.href = shopAddress + "/checkout";
}
});
});
}
With the above code I got the error Uncaught ReferenceError: submit is not defined
These functions are also the names of events, so you can work with them that way.
Assign the event name as a string, then use .on(), which takes the event name as a parameter.
You also shouldn't have multiple var x declarations. Declare it before the if, then assign it in it.
function sendToCheckout() {
$(document).ajaxComplete(function() {
var x;
if ($("form[action='/cart']").length == 1) {
x = "submit";
} else {
x = "click";
}
$("form[action='/cart']").off().on(x, function(event) {
event.preventDefault(event);
var amountToSend = sessionStorage.getItem('amountToSend');
if (amountToSend != null && amountToSend != "0") {
sendData();
} else {
window.location.href = shopAddress + "/checkout";
}
});
});
}

Uncaught TypeError: Cannot read property 'indexOf' of undefined in angularjs

I am very new to the world of coding, and need some help from experts. Below is the angularJs error I have noticed in the file:
The error is being pointed to this:
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
Your assistance will be much appreciated.
I am trying to give user suggestion based on the key which user enters.
var app = angular.module('app',[]);
app.controller('autoCompleteCTRL', function($scope, $rootScope,$http){
$rootScope.searchItems = [];
var arr= getCountries(); // Load all countries with capitals
function getCountries(){
$http.get("ajax/getCountries.php").success(function(data){
for(var i=0;i<data.length;i++)
{
$rootScope.searchItems.push(data[i].bvl_area);
}
return $rootScope.searchItems;
});
};
//Sort Array
$rootScope.searchItems.sort();
//Define Suggestions List
$rootScope.suggestions = [];
//Define Selected Suggestion Item
$rootScope.selectedIndex = -1;
//Function To Call On ng-change
$rootScope.search = function(){
$rootScope.suggestions = [];
var myMaxSuggestionListLength = 0;
for(var i=0; i<$rootScope.searchItems.length; i++){
var searchItemsSmallLetters = angular.lowercase($rootScope.searchItems[i]);
var searchTextSmallLetters = angular.lowercase($scope.searchText);
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
$rootScope.suggestions.push(searchItemsSmallLetters);
myMaxSuggestionListLength += 1;
if(myMaxSuggestionListLength == 5){
break;
}
}
}
}
//Keep Track Of Search Text Value During The Selection From The Suggestions List
$rootScope.$watch('selectedIndex',function(val){
if(val !== -1) {
$scope.searchText = $rootScope.suggestions[$rootScope.selectedIndex];
}
});
//Text Field Events
//Function To Call on ng-keydown
$rootScope.checkKeyDown = function(event){
if(event.keyCode === 40){//down key, increment selectedIndex
event.preventDefault();
if($rootScope.selectedIndex+1 !== $rootScope.suggestions.length){
$rootScope.selectedIndex++;
}
}else if(event.keyCode === 38){ //up key, decrement selectedIndex
event.preventDefault();
if($rootScope.selectedIndex-1 !== -1){
$rootScope.selectedIndex--;
}
}else if(event.keyCode === 13){ //enter key, empty suggestions array
event.preventDefault();
$rootScope.suggestions = [];
}
}
//Function To Call on ng-keyup
$rootScope.checkKeyUp = function(event){
if(event.keyCode !== 8 || event.keyCode !== 46){//delete or backspace
if($scope.searchText == ""){
$rootScope.suggestions = [];
}
}
}
//======================================
//List Item Events
//Function To Call on ng-click
$rootScope.AssignValueAndHide = function(index){
$scope.searchText = $rootScope.suggestions[index];
$rootScope.suggestions=[];
}
//======================================
});
The value of searchTextSmallLetters variable has become undefined. First you check whether it can be undefined. If so change the line to
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
or else check the service on "ajax/getCountries.php" is working and return the expected output. Since you using a get request you can use browser to do that (%domain%/ajax/getCountries.php eg:-localhost:8080/ajax/getCountries.php)
Important: Always it is good to do validations. So it is good to change the line to
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
Change the below line for proper handling
if( searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
To
if(searchItemsSmallLetters && searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1){
When "searchItemsSmallLetters" is undefined, then your condition will throw such error.

jquery error TypeError: Value not an object. with .split(',')

i am getting a strange error
Error: TypeError: Value not an object.
Source File: /Scripts/jquery-1.8.3.js
Line: 4
while i am trying to do a .split() with javascript.
Following is the snippet :
$("#item_qty_1").on("keydown", function (event) {
if (event.which == 13) {
var weight_code = $("#weight_code").val();
var qty = Number($(this).val());
if((weight_code == "2" || weight_code == "3") && qty <= 50)
{
var qty_sub_val = document.getElementById('item_qty_sub').value;
var qty_sub = "";
console.log(typeof qty_sub_val);
if(qty_sub_val != "" && qty_sub_val !== null)
{
qty_sub = qty_sub_val.split(',');
}
$("#test").html(qty_sub);
for(var i=1; i<=50; i++)
{
if(i>qty)
{
$("#qty_" + i).attr("tabindex","-1").attr("readonly","readonly").removeAttr("last").css("background","#e6e6e6");
}
else
{
if(qty_sub_val != "")
{
$("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white").val(qty_sub[i-1]);
}
else
{
$("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white");
}
}
}
$("#qty_" + qty).attr("last","0");
$("#unit1_list").modal();
}
event.preventDefault();
return false;
}
});
it is giving error only when qty_sub_val != ""; i.e. when .split(',') is called.
Please check what $("#item_qty_sub") returns. I think it is not returning the right value.

jQuery check if two values is blank

I have three values:
var tbb = $("#total1 span").text();
var tmb = $("#total2 span").text();
var tab = $("#total3 span").text();
Each of them could be blank.
What is the better way in javascript/jquery check if two of these values is blank?
UPDATE
here is what i mean, my a bit ugly and a "lot of lines" solution
var i = 0;
if (tab != "") {
i++;
}
if (tmb != "") {
i++;
}
if (tbb != "") {
i++;
}
if (i >= 2) {
//do something
}
Any better thoughts?
if(tbb == null || tbb == ''){...}
And the same for the rest.
var twoAreEmpty = $("#total1, #total2, #total3").find("span:empty").length === 2;
var twoblank =
$("#tota11 span, #total2 span, #total3 span")
.filter(function(index){
return !$(this).text().replace(/^\s+|\s+$/g, '');
})
.length === 2;
Also, you probably mean #total1, not #tota11 - just sayin.
if (tab == "") should be enough shouldn't it?
Does .text() ever return blank?
var filtered = [tmb, tbb, tab].filter(function( str ) {
return !str.length;
});
if( filtered.length === 2 ) {
console.log('yay, two empty values: ', filtered);
}
Just try it.
var i = 0;
if(tbb.length == 0 )
{
i++
}
if(tmb.length == 0 )
{
i++
}
if(tab.length == 0 )
{
i++
}
if(i >=2)
{
//perform operation
}
It's been a while, but this is going to be a single-line solution for what you want.
if (((tab == '' ? 1 : 0) + (tmb == '' ? 1 : 0) + (tbb == '' ? 1 : 0)) > 1){
// Do Something
}
All valid answers, but forgetting about undefined :)
if(tbb === '' || tbb === null || tbb === undefined){ // do stuff };
I'd recommend making it a function which could return true/false :)

Categories

Resources