The function 'toLowerCase' cannot be found for the type 'string | number | string[]'. Similarly, the function 'toLowerCase' cannot be found for the type 'number'

Currently, I am working on a Laravel project using Laravel Mix. I am attempting to create a table with filter functionality. However, when I insert the following code into my TS file:

import $ from 'jquery';
import 'bootstrap';

$(() => {
    if ($('#documents-view').length > 0) {
        $("#myInput").on("keyup", function() {
            var value = $('in').val().toLowerCase();
            $("#myTable tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });
    }
});

I encounter the following two errors:

TS2339: Property 'toLowerCase' does not exist on type 'string | number | string[]'. Property 'toLowerCase' does not exist on type 'number'.

and

TS2345: Argument of type '(this: HTMLElement) => void' is not assignable to parameter of type 'string | Element | JQuery<HTMLElement> | Element[] | ((this: HTMLElement, index: number, element: HTMLElement) => boolean)'. Type '(this: HTMLElement) => void' is not assignable to type '(this: HTMLElement, index: number, element: HTMLElement) => boolean'. Type 'void' is not assignable to type 'boolean'.

Below is my frontend code with a table within it:

@extends('client-portal::layouts.default')
@section('content')
    <div id="documents-view" class="clients">
        <div class="clients-top">
            <div class="clients-top__logo">
                <img class="clients-top__image" src="{{ asset('vendor/client-portal/images/logo_CRVS.png') }}">
            </div>
            <div class="clients-top__title">Klantportaal</div>
        </div>
        @include('client-portal::navbar')
        <div class="clients-content">
            <div class="col-md-20 offset-md-1 p-3 p-md-5">
                <div class="container-fluid">
                    <div class="row">
                        <a class="btn btn-primary mb-3 border-white" href="#">
                            {{ __('Document toevoegen') }}
                        </a>
                        <input class="form-control mb-2" id="myInput" type="text" placeholder="Zoeken..">
                        @if($documents->isEmpty())
                            <p>Er zijn geen documenten bij ons bekend.</p>
                        @else
                            <table class="table table-striped table-bordered bg-white" style="width:100%">
                                <thead>
                                <tr>
                                    @foreach($data['documents'] as $document)
                                        <th>{{$document['name']}}</th>
                                    @endforeach
                                </tr>
                                </thead>
                                <tbody id="myTable">
                                @foreach($documents as $document)
                                    <tr>
                                        @foreach($document as $key => $item)
                                            @foreach($data['documents'] as $keyConfig => $reg)
                                                @if($key === $keyConfig)
                                                    <td>{{$item}}</td>
                                                @endif
                                            @endforeach
                                        @endforeach
                                    </tr>
                                @endforeach
                                </tbody>
                                <tfoot>
                                <tr>
                                    @foreach($data['documents'] as $document)
                                        <th>{{$document['name']}}</th>
                                    @endforeach
                                </tr>
                                </tfoot>
                            </table>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
@stop

I am uncertain about the errors in my code. Can anyone assist me with resolving them?

Answer №1

With jQuery's val() method, it can return a variety of types such as string, number, string[], or undefined, so it's important to add type checks. Here's an example:

var v = $('in').val();
var defaultValue = '';
var value = typeof v === 'string' ? v.toLowerCase() : defaultValue;

Also, for the filter function, it requires additional parameters and it's crucial to include the returned value (which seems to be missing in your code).

From your code snippet, it seems like you might not actually need a filter function, but rather a forEach loop.

$("#myTable tr").forEach(function() {
  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies should be followed for managing constant types effectively in TypeScript?

enum ENUM_POSITION_TYPE { LEFT = 1, RIGHT = 2 } // type PositionType = 1 | 2 type PositionType = ??? export let a1: PositionType = ENUM_POSITION_TYPE.RIGHT //correct export let a2: PositionType = 1 as const //correct export let a3: PositionType = 3 / ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

Elegant Popup Form

I'm encountering a problem with my ajax form that is embedded within a bootstrap modal. On the first use, the form functions correctly. However, when I attempt to use it again without refreshing the page, the text area no longer appears within the mod ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Is there a way for me to determine the total number of seconds since the chatbot was first opened?

Here is a snippet of my HTML code: <div class="chatbot chatbot--closed "> <div class="chatbot__header"> <p><strong>Got a question?</strong> <span class="u-text-highlight">Ask Harry</span></p> <s ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...

Children must be matched to the route before navigating to it

Hello there! I'm having trouble understanding how to navigate new routes with children in Angular 2 rc 4. I'm trying to route to the TestComponent, which has a child, but I keep getting an error message saying "cannot match any route 'test&a ...

Incorporating Bloodhound into an Angular 2 CLI project

I have been working on integrating Bloodhound.js into an Angular 2 project that utilizes Angular 2 CLI. Currently, I have successfully implemented jQuery by following these steps: Installed jQuery using npm install jquery --save Installed jQuery Type ...

Video is not visible in safari browser initially, but becomes visible only after scrolling for a little while

Having issues with a video not displaying correctly in Safari? The problem is that the video only becomes visible after scrolling the browser window. Want to see an example of this issue in action? Click here and select the red bag. Check out the code sni ...

Interaction between a main webpage and a separate popup OAuth authorization page

I need assistance with my application that includes a button to open a blank page for LinkedIn authentication. My main query involves how to notify the original page once the user has successfully completed the authentication and processing for LinkedIn. ...

Guide on submitting form information to API controller

When using jQuery, form data is posted: $.ajax('API/Validate/Customer?column=1&rowid=2&vmnr=3&isik=4', { data: JSON.stringify({ headerData: $("#_form").serializeArray() }), async: false, cont ...

What does ngModel look like without the use of square brackets and parenthesis?

Can you explain the usage of ngModel without brackets and parentheses in Angular? <input name="name" ngModel> I am familiar with [ngModel] for one-way binding and [(ngModel)] for two-way binding, but I am unsure what it means when ngModel ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

Are you encountering a malfunctioning AJAX Function? Seeking assistance with PHP/MySQL

I have a PHP-generated form that needs to submit data using AJAX. Here's what I have so far... PHP Form <div class="user"> <span>Start a friendship with '.$row['screen_name'].'</span> <form method="PO ...

What could be causing the data toggle feature in my navbar to not work on Bootstrap?

Here is a code snippet to create a simple collapsible navbar with Bootstrap 5 that includes a logout button. However, the data toggle feature for the logout button doesn't seem to work when clicked. Any suggestions on how to fix this? <!DOCTYPE ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

Tips for transmitting dropdown selections to a different PHP form using jQuery

After spending a considerable amount of time searching for answers online, I realized that I need some help. Despite finding helpful articles and resources on jQuery, I am still struggling to understand certain concepts. As a beginner in this field, I am w ...

Sort items in a list manually using Jquery sortable feature

Is there a way to sort the listitems using either sortList[0] or sortList[1]? Example: http://jsfiddle.net/wmaqb/20/ HTML <div id="sortable"> <div id="sort_18b0c79408a72">Berlin</div> <div id="sort_dkj8das9sd98a" ...

Utilizing a datatable plugin to enhance an HTML table within a WordPress website that is connected to a database

My current WordPress site features a main HTML table with a basic header of 7 columns. The rows in this table are filled from a database variable, and it works flawlessly. Recently, I was tasked with making this entire table sortable, filterable, and searc ...