Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable all text areas except for the first one. Alternatively, if one of the textareas has content, I want to disable the ones with empty values. Here is a snippet of my current code:

Typescript/Jquery

thisMethod(): any {
    this.check.subscribe(val => {
        if (val === true) {
            $("textarea[name='text']").each((i, element) => {
                 if ($(element).val() === "") {
                     if (i !== 0) {
                         $(element).prop('disabled', true);
                     };
                 }
                 else {
                      // some check for populated textbox to disable unpopulated checkboxes
                 }
            }
        }
    }
}

HTML

<div data-bind="foreach: choice">
    <-- ko if: hasData($data) -->
    <div>
        <textarea class="form-control" name="text" data-bind="attr: {id: $data + '-choice-text'}, event: {change: $root.anonClass.thisMethod}"></textarea>
    </div>
</div>

I'm struggling to understand the behavior of JQuery's .each() function. Does it validate each element individually before moving to the next condition or does it iterate like a traditional for loop?

When testing just the first if block, I notice that nothing seems to happen. This issue may be unrelated to JQuery and could potentially be due to the knockout change event not firing, though I am uncertain.

Answer №1

Instead of using .each() to loop through the set, have you considered logging all the elements inside the function to ensure proper selection?

While your code is almost functioning correctly, it seems to always leave the first element enabled, regardless of other values present.

A potential alternative approach could be:

  • Identify and disable all empty textareas
  • If all textareas are empty, re-enable only the first one

$('#check').click(() => {
  const $areas = $('textarea');
  
  const $emptyAreas = $areas.filter((i,t) => !t.value);
  $emptyAreas.prop('disabled', true);
  
  if ($emptyAreas.length === $areas.length) {
    // all empty
    $areas.first().prop('disabled', false);
  }

});

$('#reset').click(() => $('textarea').prop('disabled', false).val(''));
textarea {
display:block;
margin-bottom:1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button id="check">check</button>
<button id="reset">reset</button>

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

Jquery cannot be used to set a value for an ASP .net hidden field

Having trouble setting the value of a hidden field using jQuery in ASP .NET. The hidden field is defined as follows: <asp:HiddenField runat="server" ID="hdnSelectedTicket" /> This is how I am attempting to set the value: alert(ticketI ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

Decoding an array of objects

I am struggling to parse the array of objects in my JSON file, which looks like this: { "@name": "zlib License", "component": [{ "name": "iCarousel", "url": "http://github.com/nicklockwood/iCarousel/" }, { "name": "FXKe ...

Accessing a PHP page on Cordova PhoneGap through AJAX

I am trying to display my php page within an android mobile app using Cordova. I have added a php page in my project with the directory "php/load.php". However, when attempting to show this page on index.html, the following code does not work. <button ...

Ways to verify if the inner <div> contains any text

I am attempting to determine if the inner <div> contains the text "Ended" and then remove it if it does. There are multiple <div> elements with the same class. I have attempted to use the .filter() method. My goal is to remove the container_one ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

The jQuery autocomplete feature with typeahead suggestions fails to appear following a successful AJAX request

I am currently using typeahead.js to incorporate tags into my multiple input setup. The tagging function works as expected, however, I am facing an issue where the autocomplete suggestions are not appearing. Is there a solution to fix this problem? Despit ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...

How can I use AJAX to update a DIV when an image is swapped out?

I run an online radio station and I've been looking for a way to display album artwork for each song that plays. After setting up the ability to automatically upload the image of the currently playing song as "artwork.png" to a web server via FTP, I c ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Assist me with Twitter

Seeking assistance with a coding issue related to displaying Twitter posts on a website. I have found a code snippet that accomplishes this: //Scrolling of tweets in the footer $(function () { var tweetVP = $("#footerTweetsViewport"); arrTweetNav ...

How to retrieve plain text data from a jQuery ajax call to a PHP server

Having trouble getting my ajax request to a php page to return plain text. Here's the code snippet: $.ajax({ type: 'GET', url: '/shipping/test.php', cache: false, dataType: 'text', ...

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

What is the most efficient method for clearing the innerHTML when dealing with dynamic content?

Is there a more efficient method for cleaning the innerHTML of an element that is constantly changing? I created a function to clean the containers, but I'm not sure if it's the most efficient approach. While it works with the specified containe ...

Looping through AJAX requests in JavaScript

I am attempting to make REST API requests in order to retrieve data and display it on a website. Although I have created a for loop to gather the data, I am encountering an issue where the data is not being displayed on the website. Upon checking with th ...

Storing Global Types in Angular: A Better Approach

Imagine I possess certain universally applicable enums, interfaces, or extensive classes. For example: export interface LogMessage { code: number; message: string; } Where would be the optimal location to store them? What is considered the best pr ...

JQuery Ajax: Issue with updating Total Likes for posts when Like button is clicked

There are two JQuery Ajax calls in this scenario. The first call retrieves user messages from MySQL, along with the number of likes for each message and a button for users to like the message. This initial request is functioning correctly. The second Ajax ...

Tips for sending an array of "FormData" through ajax and retrieving it in a Laravel controller

# Could you please provide guidance on sending this array to the controller via Ajax request? var dataPanier=[]; function addarray(objser) { dataPanier.push(objser); } $('.target').click(function() { var btn_name=$(this).attr("name"); ...

Regular intervals and asynchronous JavaScript and XML (AJAX) requests are

There is a simple chat tool in place to ensure the chat room stays updated: setInterval (loadLog, 2500); function loadLog(){ //Scroll height prior to the request var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20; ...

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...