Cannot read property tolowercase of undefined ошибка

Есть прогрессбар, в котором ползунок должен двигаться от 1 до 95% в соответствии со значением из input-а.
В input можно ввести значение от 1 до 1000.
Также есть дополнительные кнопки, которые устанавливают автоматические значения в него: минимальное/максимальное, больше/меньше и удвоить текущее значение.
Проблема у меня в том, что при вводе значения вручную прогрессбар заполняется нормально. Но при нажатии на кнопки появляется ошибка «Uncaught TypeError: Cannot read property ‘toLowerCase’ of undefined».
Не могу понять как мне из функции lessOrMore() правильно запустить функцию progressBar(), передав в неё получившееся значение.

html:

<div class="w-wheel">
  <div class="wheel">
    <div id="cont" data-pct="1">
      <svg id="svg" width="200" height="200" viewPort="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <circle r="90" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle>
        <circle id="bar" r="90" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle>
      </svg>
    </div>
    <div class="w-controlBtn">
      <span class="controlBtn min">мин</span> 
      <span class="controlBtn controlBtn--step minus">-</span>
      <input id="percent" name="percent" type="text" placeholder="Ставка..." value="">
      <span class="controlBtn controlBtn--step plus">+</span> 
      <span class="controlBtn max">макс</span>
      <span class="controlBtn double">удвоить</span>
    </div>
  </div>
</div>

css:

.wheel {
  margin-top: 45px;
  #svg {
    transform: rotate(90deg);
  }
  #svg circle {
    stroke-dashoffset: 0;
    transition: stroke-dashoffset 1s linear;
    stroke: #666;
    stroke-width: 1.3em;
  }
  #svg #bar {
    stroke: #FF9F1E;
    stroke-dashoffset: 559.832px;
  }
  #cont {
    display: block;
    height: 200px;
    width: 200px;
    margin: 0 auto;
    border-radius: 100%;
    position: relative;
  }
  #cont:after {
    position: absolute;
    display: block;
    height: 160px;
    width: 160px;
    left: 50%;
    top: 50%;
    content: attr(data-pct)"%";
    margin-top: -80px;
    margin-left: -80px;
    border-radius: 100%;
    line-height: 160px;
    font-size: 2em;
    text-align: center;
  }

  input {
    color: #000;
    height: 50px;
    line-height: 50;
    width: 200px;
    border: 1px solid rgba(0,0,0,.1);
    border-radius: 25px;
    padding-left: 65px;
  }
  .w-controlBtn {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    margin-top: 55px;
  }
  .controlBtn {
    cursor: pointer;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    &.min {
      margin-right: 10px;
    }
    &.max {
      margin-left: 10px;
    }
    &.minus {
      margin-right: -50px;
    }
    &.plus {
      margin-left: -50px;
    }
    &.double {
      flex-basis: 100%;
      margin-top: 10px;
    }
  } 
  .controlBtn--step {
    color: #fff;
    background-color: orange;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    z-index: 2;
    font-weight: bold;
  }
}

js:

function lessOrMore() {
    var inputValue = $('#percent').val();
    if($(this).hasClass("min")){
      inputValue = 1;
    }
    else if($(this).hasClass("max")){
      inputValue = 1000;
    }
    else if($(this).hasClass("plus")){
      inputValue++;
    }
    else if($(this).hasClass("minus")){
      inputValue--;
    }
    else if($(this).hasClass("double")){
      inputValue *= 2;
    }

      if (isNaN(inputValue)) {
       inputValue = 95; 
      }
      else{
        if (inputValue <= 1) { inputValue = 1;}
        if (inputValue > 1000) { inputValue = 1000;}
      }    

    $('#percent').val(inputValue);
progressBar(inputValue)
}

function progressBar(val){
  var val = parseInt($(this).val());
  var $circle = $('#svg #bar');

  if (isNaN(val)) {
   val = 95; 
  }
  else{
    var r = $circle.attr('r');
    var c = Math.PI*(r*2);
    if (val < 0) { val = 0;}
    if (val > 95) { val = 95;}

    var pct = ((100-val)/100)*c;

    $circle.css({ strokeDashoffset: pct});

    $('#cont').attr('data-pct',val);
  }
}

$('#percent').on('input', progressBar);
$('.controlBtn').on('click', lessOrMore);

Version

v2.8.1

Reproduction link

https://cmty.app

Steps to reproduce

Sorry for no repo as I’m not sure what is causing this but I’l do my best to explain what I found out
This issue is caused by the ssr trying to render the page and finding a comment block
brave_2uQ9VVuJnD.png
brave_n8Yrq1ABy1.png
This comment appears under the __nuxt div:
brave_EerK58t9i3.png

I have no idea why is this comment showing up there.

This is a random issue, as removing node modules and package.lock then reinstalling (might) fix this, or it might not, it might cause it, randomly.
Honestly I’ve been trying to solve this for the last 2 days and I’m about to lose my mind about that comment that just shows up and disappears every time

Please help and dont shun me for not opening a repo I just cant.

What is expected ?

explained above

What is actually happening?

explained above

This bug report is available on Nuxt community (#c9537)

To fix the TypeError: cannot read property of ‘toLowerCase’ of undefined error, you need to check if the property exists before calling toLowerCase() function using the “ternary operator”.

The TypeError: cannot read property of ‘toLowerCase’ of undefined error occurs in JavaScript when you try to call the toLowerCase() method on an undefined value. This method can only be used on strings, so you must ensure that the value you are passing to it is a string and not undefined.

Reproduce the error

let person = {
  name: "Krunal",
  age: 30
};

let gender = person.gender.toLowerCase();

console.log(gender)

Output

TypeError: Cannot read properties of undefined (reading 'toLowerCase')

Solution 1: Using the ternary operator

Use the ternary operator(?) to check if the property exists before calling toLowerCase() function.

let person = {
  name: "Krunal",
  age: 30
};

let gender = person.gender ? person.gender.toLowerCase() : "";

console.log(gender)

Output

We get the empty string in the output because the gender property does not exist in the person object.

Using the ternary operator, we checked if it exists, and if it does not, then we set the gender property to empty, which escapes the TypeError.

Solution 2: Using optional chaining (?.)

let str = undefined

let res = str.toLowerCase()

console.log(res)

Output

TypeError: Cannot read property 'toLowerCase' of undefined

The above code example will throw an error because you cannot call a method (in this case, toLowerCase()) on an undefined value. You need to assign a string value to str before you can call toLowerCase().

If you try to call toLowerCase() on an undefined value, you will receive a TypeError with the message “Cannot read property ‘toLowerCase’ of undefined”.

let str = undefined

let res = str?.toLowerCase() || '';

console.log(res)

Output is an empty string.

That’s it.

TypeError: Cannot read property ‘toLowerCase’ of undefined error javascript [closed]

function onChatHandler(target, context, msg, self) {
if (self) { return; }

const xxs = ["asd","asdw"];
const commandName = msg.trim();
if (xxs.some(word => msg.content.toLowerCase().includes(word))) {
  const num = rollDice();
  client.say(target, `Gelen sayi ${num}`);
  console.log(`* Bu ${commandName} komut kullanildi.`);
 
}

TypeError: Cannot read property ‘toLowerCase’ of undefined error

Advertisement

Answer

String.prototype.toLowerCase is for a string. Value prototypes don’t work on an undefined value (e.g: undefined.forEach or undefined.keys), nor do they work for values that don’t belong to that prototype of that value (e.g: "string".push).

This error means that you are calling .toLowerCase on a value that is undefined, so, using logic we can conclude that msg.content is undefined.

To fix it, I recommend some debugging (try to console.log msg if you can, and see what it contains).

  • Remove From My Forums
  • Question

  • User1078534304 posted

    Hi Everyone,

    Please help me on this error. It  seems like i cannot use the ‘toLowerCase’ function from the javascipt.

    my codes:

    /// <reference path="../Scripts/jquery-1.7.1.min.js" />
    /// <reference path="../Scripts/jquery-1.5.2.js" />
    /// <reference path="../Scripts/knockout-2.3.0.js" />
    /// <reference path="../Scripts/knockout-3.1.0.js" />
    /// <reference path="../Scripts/jquery-1.9.0.js" />
    /// <reference path="../Scripts/jquery-2.0.0.js" />
    /// <reference path="../Scripts/jquery-1.10.2.js" />
    
    /* /// <reference path="../Scripts/jquery.js" />
    /// <reference path="../Scripts/jPaginate.js" />
    */
    function CleanData() {
        document.getElementById("txtCustname").value = null;
        document.getElementById("txtCustNRIC").value = null;
        document.getElementById("txtEmail").value = null;
        document.getElementById("txtContactNo").value = null;
    };
    
    function QCust(data) {
        this.custno = ko.observable(data.custno);
        this.custname = ko.observable(data.custname);
        this.custemail = ko.observable(data.custemail);
        this.custclass = ko.observable(data.custclass);
        this.custnric = ko.observable(data.custnric);
        this.custcontact = ko.observable(data.custcontact);
    };
    
    function QCustClass(classdata) {
        this.classid = ko.observable(classdata.classid);
        this.classcode = ko.observable(classdata.classcode);
        this.classdesc = ko.observable(classdata.classdesc);
        this.classisactive = ko.observable(classdata.classisactive);
    };
    
    var QChoiceType = function (choicetype, choicetypedisplay) {
        var self = this;
        self.choicetype = choicetype;
        self.choicetypedisplay = choicetypedisplay;
    };
    
    //ko validations
    ko.extenders.required = function (target, overrideMessage) {
        //add some sub-observables to our observable
        target.hasError = ko.observable();
        target.validationMessage = ko.observable();
    
        //define a function to do validation
        function validate(newValue) {
            target.hasError(newValue ? false : true);
            target.validationMessage(newValue ? "" : overrideMessage || "*");
        }
    
        //initial validation
        validate(target());
    
        //validate whenever the value changes
        target.subscribe(validate);
    
        //return the original observable
        return target;
    };
    
    var QModel = function (questions) {
        var appPath = window.location.pathname;
        var self = this;
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth() + 1;
        var year = date.getFullYear();
        if (month < 10) month = "0" + month;
        if (day < 10) day = "0" + day;
        var today = year + "-" + month + "-" + day;
    
        self.classid = ko.observable();
        self.classcode = ko.observable();
        self.classdesc = ko.observable();
        self.classisactive = ko.observable();
        self.strsearch = ko.observable();
        self.customers = ko.observableArray();
        filteredcustomers = ko.observableArray();
        searchcustomers = ko.observableArray();
        self.custno = ko.observable();
        self.custname = ko.observable().extend({ required: "*" });
        self.custnric = ko.observable().extend({ required: "*" });
        self.custemail = ko.observable().extend({ required: "*" });
        self.custcontact = ko.observable().extend({ required: "*" });
        self.custdob = ko.observable(today);
        self.custjoindate = ko.observable();
        self.custclass = ko.observable();
        self.custisactive = ko.observable();
        self.isError = ko.observable();
        self.customerclasses = ko.observableArray();
        self.selectedcustomerclass = ko.observable().extend({ required: "*" });
        self.totalitems = ko.observable();
        self.search = ko.observable();
        self.questions = ko.observableArray(
             ko.utils.arrayMap(questions, function (question) {
                 return { formId: question.formId, groupId: question.groupId, qString: question.qString,
                     choices: ko.observableArray(question.choices)
                 };
             })
        );
    
    
        selectedChoiceType = ko.observable();
        availableChoiceType = ko.observableArray([new QChoiceType("checkbox", "Checkbox"),
                                                       new QChoiceType("text", "Text"),
                                                       new QChoiceType("radio", "Option Button")
                                                      ]);
    
        self.ClearFields = function () {
            self.custno = ko.observable();
            self.custname = ko.observable().extend({ required: "*" });
            self.custnric = ko.observable().extend({ required: "*" });
            self.custemail = ko.observable().extend({ required: "*" });
            self.custcontact = ko.observable().extend({ required: "*" });
            self.custdob = ko.observable(today);
            self.custjoindate = ko.observable();
            self.custisactive = ko.observable();
        };
    
        //*** check if customer is existing ***
        self.isCustomerExists = function (customer) {
            var dtJoinDate = new Date();
            var cust = customer;
            $.post(appPath + "/Customers/IsCustomerExisting", cust, function (data) {
                return data;
            });
        };
    
        //*** save customer ***
        self.saveCustomer = function (customer) {
            var cust = customer;
    
            $.post(appPath + "/Customers/SaveCustomer", cust, function (data) {
                var isSaved = (data === "True")
                if (isSaved) {
                    alert("Customer has been added");
                    self.ToggleNewCustomerOff();
                }
                else {
                    alert("Unable to add customer");
                }
            });
        };
    
        self.insertcustomer = function () {
            var dtJoinDate = new Date();
            var cust = {
                CustNo: self.custno,
                CustName: self.custname,
                CustNRIC: self.custnric,
                CustEmail: self.custemail,
                CustContact: self.custcontact,
                CustDOB: self.custdob,
                CustJoinDate: dtJoinDate,
                CustClass: self.selectedcustomerclass,
                CustIsactive: self.custisactive
            };
    
            $.post(appPath + "/Customers/IsCustomerExisting", cust, function (data) {
                var isExisting = (data === "True");
                if (isExisting) {
                    alert("the Customer is already existing");
                }
                else {
                    self.saveCustomer(cust);
                }
            });
        };
    
        self.searchCustomer = function () {
            self.ToggleNewCustomerOff();
    
            var data = {
                search: self.strsearch
            };
    
            $.post(appPath + "/Customers/SearchCustomer", data,
                            function (customerdata) {
                                debugger;
                                var custs = ko.toJSON(customerdata);
                                var mappedData = $.map(customerdata, function (item) {
                                    return new QCust(item);
                                });
                                self.customers(mappedData);
                                self.totalitems = customerdata.length;
                                //                            $("#total_items").attr('value', self.totalitems);
                                //                            $("#content").jPaginate();
                            });
        };
    
        self.updateThis = function (jsonData) {
            var jsonString = JSON.stringify(jsonData);
            var parsed = JSON.parse(jsonString);
            alert(jsonData);
        };
    
        self.addQuestion = function () {
            self.questions.push({
                formId: ko.observable(),
                groupId: ko.observable(),
                qstring: ko.observable(),
                choicetype: ko.observable(),
                choices: ko.observableArray()
            });
        };
    
        self.addChoice = function (questions) {
            questions.choices.push({
                chtype: ko.observable(),
                cstring: ko.observable()
            });
        };
    
        self.removeChoice = function (choice) {
            $.each(self.questions(), function () {
                this.choices.remove(choice)
            })
        };
    
        self.removeQuestion = function (question) {
            self.questions.remove(question);
        };
    
        self.ToggleSearch = function () {
            $("#divNewCustomer").show();
        };
    
        self.ToggleNewCustomerOn = function () {
            self.custname("");
            self.custnric("");
            self.custemail("");
            self.custcontact("");
            self.LoadClass();
            $("#divNewCustomer").show();
            $("#divCustomerList").hide();
        };
    
        self.ToggleNewCustomerOff = function () {
            self.custname("");
            self.custnric("");
            self.custemail("");
            self.custcontact("");
            $("#divNewCustomer").hide();
            $("#divCustomerList").show();
        };
    
        self.saveQuestions = function (question) {
            var qToJSON = ko.toJSON(this);
            alert(qToJSON.toString());
        };
    
        $.post(appPath + "/Customers/GetCustomerLists",
                                function (customerdata) {
                                    debugger;
                                    var mappedData = $.map(customerdata, function (item) {
                                        return new QCust(item);
                                    });
                                    self.customers(mappedData);
                                });
    
        //*** comparison of the string for search ***
        self.filtercustomers = ko.computed(function () {
            var searchText = self.search().toLowerCase;
            if (!searchText) {
                return self.customers();
            }
            else {
                if (self.customers() != 'undefined' && self.customers() != null && self.customers().length > 0) {
                    return ko.utils.arrayFilter(self.customers(),
                        function (cust) {
                            return cust.custname.toLowerCase().indexOf(searchText) > -1;
                        });
                }
            }
        });
    
        //*** end of the comparisons ***
    
        //*** get records from the database
        //    self.LoadData = function () {
        //        debugger;
        //        $.post(appPath + "/Customers/GetCustomerLists",
        //                        function (customerdata) {
        //                            debugger;
        //                            var mappedData = $.map(customerdata, function (item) {
        //                                return new QCust(item);
        //                            });
        //                            self.customers(mappedData);
        //                            self.totalitems = customerdata.length;
        //                            //                            $("#total_items").attr('value', self.totalitems);
        //                            //                            $("#content").jPaginate();                        
        //                        });
        //    };
    
    
        self.LoadClass = function () {
            $.post(appPath + "/Customers/GetCustomerClass",
                    function (customerclass) {
                        var mappedData = $.map(customerclass, function (item) {
                            return new QCustClass(item)
                        });
    
                        self.customerclasses(mappedData);
                    });
        };
    
        $("#divNewCustomer").hide();
    
        filter = ko.observable();
    };
    
    debugger;
    var qm = new QModel();
    var path = window.location.pathname;
    
             
    ko.applyBindings(qm);

    my mvc code:

    <input data-bind="value: search, valueUpdate: 'afterkeyup'" type="text" style="height:30px;width:98%;text-indent:5px;"/>
    
    <div data-bind="foreach: filtercustomers">
       <p data-bind="text: custname"></p>
    </div> 

    Thanks and best regards,

    Nusij

Answers

  • User681112540 posted

    toLowerCase() is a method, you miss the bracket at the end of toLowerCase in your code.

      self.filtercustomers = ko.computed(function () {
            var searchText = self.search().toLowerCase();
            if (!searchText) {
                return self.customers();
            }
    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1918509225 posted

    Hi Nusij03,

    You have miss bracket for your toLowerCase method,just like below:

    var str = "Hello World!";
    var res = str.toLowerCase();
    

    not

    var res=str.toLowerCase;

    Here is link which you can refer to :

    http://www.w3schools.com/jsref/jsref_tolowercase.asp

    Best Regards,

    Kevin Shen

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Возможно, вам также будет интересно:

  • Cannot read properties of undefined reading length ошибка
  • Cannot read properties of null reading classlist ошибка
  • Cannot read from port ошибка
  • Cannot place this file no filter found for requested operation ошибка indesign
  • Cannot perform a dml operation inside a query ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии