Reiterating the text and determining the length of the string

Currently, the script is capable of calculating the width of the script based on user input and can also determine the width of a string. However, I am facing an issue when attempting to repeat a string entered by the user. For example, if the user inputs "A" and then repeats it 6 times resulting in "AAAAAA", that's where the problem arises. The function created for repeating the string is not functioning as intended. Essentially, the goal is to repeat the string a certain number of times and then calculate its width. Any suggestions on how to resolve this issue?

$.fn.textWidth = function(text, font) {

    var fontsize = $('#fntSize').val();

    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css({'font-size':fontsize+'px'});
    return $.fn.textWidth.fakeEl.width();
};

$.fn.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

$("[name='txtLine[]']").each(function(){

    $(this).css({"background-color":"#fff"}).siblings('span.errorMsg').text('');;



    if (!this.value.length) 
    {
        $(this).focus();
        $(this).css({"background-color":"#f6d9d4"}).siblings('span.errorMsg').text('Please add a word.');
        event.preventDefault();
    }


    if($(this).repeat(6).textWidth() >= 490)
    {
        alert("Too long");
        event.preventDefault();


    }

}); 


});

Answer №1

$(this).repeat(6).textWidth() should actually be this.value.repeat(6).textWidth(). Remember, $(this) is a jQuery object, not a string.

If you want to create a method that works with regular strings, make sure to add it to the String prototype instead of defining it as a jQuery method:

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

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

Ensuring Checkbox State Persistence and Posting Values to Page Upon Next Pagination Page Click or Page Refresh - A Guide

What is the optimal method for preserving and posting the state of selected checkboxes even after a page refresh? I am facing an issue where, upon implementing pagination to navigate through MySQL database results based on checkbox filters, the checked che ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...

Conceal the title attribute when hovering over a link using javascript/jquery

I have implemented the title attribute for all my links, but I want it to be hidden during mouse hover while still accessible to screen readers. var linkElements = document.getElementsByTagName('a'); for (var index = 0; index < linkElements. ...

Updating jQuery event behaviors based on the value of .html( 'string' )

Visit this link for more information. Feel free to modify the heading if you believe it needs improvement. General I manage a multilingual WordPress website with dynamic menu and navigation controlled through the WordPress admin panel. The multilingual ...

Verify if the second list item contains the "current" class

When displaying a list of blog items on the blog page, I am using grid-column: 1 / -2;. In the first row, the first blog item spans two columns while the second and subsequent rows display three items in each row. This setup works well, but when moving to ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

Is there a way to configure my datepicker so that it displays only dates that are later than a specified date

At the heart of my inquiry lies a dilemma: I have two date pickers, one for leave_start and the other for leave_end. If an individual selects "YES" for a future text_field, I aim to ensure that the date pickers only display dates after the person's an ...

Styling limitations encountered when using lang="scss" with scoped css

My current project involves using Quasar and I am attempting to style the first column of q-table: <style lang="scss" scoped> td:first-child { background-color: #747480 !important; } </style> Unfortunately, this code does not seem to have a ...

Using AJAX in a knockoutjs Form Demonstration

I need help creating a basic form using Knockoutjs to send user information via AJAX. Is there an example available that includes three fields (firstname, lastname, postal-code)? The form should either populate with values from the server if available or d ...

Discover which students have conflicting schedules with themselves

To put it simply, my question involves a table display where student numbers (USN) are concatenated in groups and the entire row is displayed using a foreach loop. Row 1: Subject 1 - 22/07/2015 - 08:00 - 1XX10XX086, 1XX10XX087, 1XX09XX088 Row 2: Subject ...

What methods can I utilize to persuade Internet Explorer to directly show the content of application/json instead of prompting to download it?

While troubleshooting jQuery applications that utilize AJAX, I often find myself needing to inspect the JSON data returned by the service in the browser. To do this, I simply input the URL for the JSON data into the address bar. One advantage of using ASP ...

Apply this class exclusively for mobile devices

Is there a way to add the class p-5 only for mobile devices? For desktop computers: <nav class="navbar navbar-expand-lg navbar-light bg-light" style="padding:0px 10px 0px 10px;"> For mobile devices: <nav class="navbar navbar-expand-lg navbar-l ...

Verify the existence of the linked page's href url

Is there an elegant way to verify if a hyperlink on a website directs to a page that returns an HTML 200 code? I'd like to give users the ability to input their own links in a model, but I also want to block any links leading to a 500 or 404 error pag ...

Event Triggered Upon Element Addition to DOM: JQuery Livequery Equivalent in Version 1.7

Is it possible to trigger an event when a certain element is added to a page, especially when I am using a Chrome extension and do not control the source page? I have explored the capabilities of JQuery 1.7's on() method, but it seems to focus on spe ...

`The font appears extremely thin when viewed on Safari and iOS devices.`

I'm struggling to resolve the issue with super-thin fonts on Safari/iOS despite trying all recommended solutions. Here is the comparison: https://i.stack.imgur.com/5DVHz.png The _document.js file: import Document, { Html, Head, Main, NextScript } fr ...

ScrollSpy Plugin in JQuery - Implementing automatic vertical text scrolling with dynamic height customization

I have been using this code to display the most recent user comments on my website, where some comments are concise while others are more lengthy. If you inspect the source code, you will notice that the height is set to 90px and overflow is set to hidden ...

Unique text: "Personalized button design without using SVG

I've been experimenting with creating a button using SVG, but unfortunately, it seems that SVG is not supported on Next.js & Material UI. Below you'll find the code snippet and screenshot I have been working with. Any help or guidance would be g ...

Using jQuery's deferred.done method to send an array of data to the done function

I followed the method outlined in https://api.jquery.com/jquery.when/ to execute a series of ajax calls (using the example $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) on that page). The code below is functional; however, I am struggling with ...