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

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

Setting the minDate for a jQuery Calendar Picker

I am currently working with two date pickers, which are described below: Date Picker 1: txtDate HTML: Date : <input type="text" id="txtDate"/> JQuery: $(function() { $("#txtDate").datepicker({ changeMonth : true, chang ...

Is it possible for flex-grow to affect images? What steps can I take to identify any issues within my code?

<section> <div class="section-header"> <h5>Discover Our Team</h5> <h1>Meet the Experts</h1> <h5>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt, eaque.</h5> ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

Resolve the issue of Dojo images not appearing on a div in Internet Explorer

I am trying to incorporate images into a dojo chart using the given code: var l_images = ["images/clearnight.png","images/clear.png","images/partlyCloudy.png","images/cloudy.png","images/showers.png","images/rain.png","images/thunderstorms.png","images/ic ...

Protecting against overflow for text inside a container that changes when hovered over

There is text displayed on top of an image within a div container that functions as a link. <a href="https://link.com" style="color:white"> <div class="thumbnail"> <img src="image.jpg" clas ...

Most effective method for automatically scrolling down upon page load

Below is the code snippet that I am using: <script type="text/javascript"> window.onload = function () { window.scrollBy(0, 100); } </script> The purpose of this code is to scroll down after the page has fi ...

"Using html_attr with the attribute "href" does not return any value in the rvest package

My objective is to extract the URLs linked with specific CSS elements on a website using rvest. Despite trying various methods, such as using the html_attr function with the 'href' argument, my current script only returns NA values instead of the ...

Enhancing the Strength of Password Generator

Example of a Simple Password Generator: function createPassword() { var characters = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOP" + "1234567890" + "@\#\-!$%^&*()_+|~=`{}\[\]:\";& ...

Can Angular Flex support multiple sticky columns at once?

I am trying to make the information columns in my angular material table stay sticky on the left side. I have attempted to use the "sticky" tag on each column, but it did not work as expected. <table mat-table [dataSource]="dataSource" matSort class= ...

customized webpage redirection based on visitor's IP address

I need assistance with redirecting the URL based on the visitor's IP address. The code I have seems to only direct visitors to AU, with all other conditions not working as expected. Any help would be greatly appreciated. Thank you! <script languag ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

JSONP request resulted in a syntax error

I'm having trouble retrieving data from a JSONP source, as it keeps throwing a Syntax error when the function is called. I am quite new to this subject and find it hard to understand why this error occurs. It seems like my understanding of JSONP reque ...

Saving a session variable to the database using ajax technology

If you're like me and struggling to figure out how to add a session variable (username) to a database using ajax, I've been there. My limited knowledge of jQuery and JavaScript made it quite the challenge. The dynamic table I'm working with ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

"Using Java HttpServlet to send data as a Gson string, then retrieving it in JavaScript as

On the server side, I have this Java code snippet: public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json;charset=UTF-8"); resp.setHeader("Cache-Control", "no-cach ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

Tips for refreshing an angularjs $scope using $.get jquery

Attempting to implement the code below using $scope: var scopes = "https://www.googleapis.com/auth/contacts.readonly"; setTimeout(authorize(), 20); function authorize() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, h ...

The font weight is failing to take effect

I'm having an issue with the font-weight in my CSS. On my website, I'm trying to decrease the font-weight but even the lightest weight (100) looks too heavy like this: https://i.stack.imgur.com/6dwFa.png However, I want it to look more like this ...