Issues with dynamically adding or removing scroll in jQuery are not being resolved

I am trying to implement a dynamic scrolling feature in my post scenario. The goal is to automatically add a vertical scroll when the number of dynamic inputs reaches a certain threshold. Specifically, if there are more than 5 dynamic inputs created, a vertical scroll should be added to prevent the div from extending beyond the body height. Additionally, the scroll should be removed when the user removes inputs and the total falls below 5. However, my code doesn't seem to be working as expected.

$(document).ready(function() {
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    console.log('check length', wrapper.length);

    var add_scroll = wrapper.css("overflow", "scroll");
    var remove_scroll = wrapper.css("overflow", "hidden");

    function checkForScroll() {

        if (wrapper.length > 5) {
            add_scroll;
        }
        if (wrapper.length < 5) {
            remove_scroll;
        }
    }
    checkForScroll();


    
    var x = 1; //initial text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
            checkForScroll()
            console.log('check length', wrapper.length);

        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
        checkForScroll()
        console.log('check length', wrapper.length);

    })
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>


</head>

<body>
      <div class="input_fields_wrap">
            <button class="add_field_button">Add More Fields</button>
            <div><input type="text" name="mytext[]"></div>
        </div>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <script src="./js/test.js"></script>

</body>

</html>

Answer №1

It appears that there is an attempt to create function pointers (or function variables if preferred)

var add_scroll = wrapper.css("overflow", "scroll");
var remove_scroll = wrapper.css("overflow", "hidden");

function checkForScroll() {
    if (wrapper.length > 5) {
        add_scroll;
    }
    if (wrapper.length < 5) {
        remove_scroll;
    }
}
checkForScroll();

Since jQuery uses chaining, most calls will return the original jQuery object, so:

var add_scroll = wrapper.css("overflow", "scroll");
add_scroll === wrapper

Therefore, calling add_scroll; has the same effect as wrapper; or $("#wrapper") - meaning it does nothing.

The solution is to convert them into functions and then call them as such;

var add_scroll = function() { wrapper.css("overflow", "scroll") };
...
add_scroll();  

Next, when you execute:

var wrapper = $(".input_fields_wrap");

only the div with class "input_fields_wrap" is returned. Since there's only one of these, wrapper.length will always equal 1.

To count how many inputs are inside the wrapper, change the check to:

wrapper.find("input").length

Instead of checking for ..length > 5 and ..length < 5, handle the case where length === 5 by using a simple if/else statement

if (wrapper.find("input").length > 5)
    add_scroll();
else
    remove_scroll();

You can simplify your code further by using the same test for the maximum limit without keeping track of exact numbers:

$(document).ready(function() {
  var max_fields = 100; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID
  
  var add_scroll = function() { wrapper.css("overflow", "scroll"); };
  var remove_scroll = function() { wrapper.css("overflow", "hidden"); };

  function checkForScroll() {
    console.log("input length", wrapper.find("input").length)
    if (wrapper.find("input").length > 5)
      add_scroll();
    else 
      remove_scroll();
  }
  checkForScroll();

  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (wrapper.find("input").length < max_fields) {
      //max input box allowed
      $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
      checkForScroll()
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    checkForScroll()
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div><input type="text" name="mytext[]"></div>
</div>

If you run this snippet, it adds scroll bars but doesn't make them scroll since the wrapper div expands to fit the content.

To enable scrolling, set a max-height, which brings us back to setting

max-height:500px;overflow-y:auto;
(adjust height based on inputs) :)

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

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Anticipating that the input in the search bar will be displayed on the search results page

Main Code in views.py from weatherbot.models import Question from django.template import RequestContext from django.shortcuts import render_to_response def search(request): query = request.GET.get('q') if query: ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

CodeIgniter Flexi Auth - Redirect users promptly upon login expiration

Is it possible to use the CodeIgniter Flexi Auth library to redirect a user to the login page immediately upon session expiration, displaying a message stating: "Your login has expired, please login again," rather than waiting until page load? I'm co ...

Key query when incorporating Jquery with PHP to create ajax requests

I'm facing a fundamental query regarding the use of jQuery with PHP for AJAX calls in terms of performance. Should I opt for a GET or a POST method? Which one provides faster results when making AJAX calls. Even though this question is not directly re ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...

If the value of the first input is zero, display "PAID" as the value of the second input. If the value of the first input is not zero, display "NOT PAID" as the value of the second input

When the value of the first input in HTML is 0, then display "PAID" as the value of the second input. If the value of the first input is not 0, then show "NOT PAID" as the value of the second input. <label>Balance Amount</label> / ...

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

Issue with child prop not being updated despite changes in parent component

I'm facing a strange issue where altering a child component's prop doesn't trigger a re-render. Here's the scenario: In the parent component, I have: <child :problemProp="proplemPropValue"></child> In the child component, ...

Encountering an issue with the history module when utilizing the webpack dev server

I am encountering an issue while trying to run webpack dev server. The history functionality was working fine until I started using the webpack module. A warning message appeared in my console: WARNING in ./src/history.js 2:15-35 export 'createBrows ...

Obtaining User Input in React JS within the Fetch Statement

I've written a code to fetch weather data from an API. Currently, the location is set to "chennai" in the link provided. I'd like to make this location user-dependent. How can I achieve this using React? import React,{useState,useEffect} from ...

Using ajax for sending data is a breeze, but I am encountering trouble when attempting to receive data back from

I have a function that retrieves a value from an input and sends data through ajax to another PHP file. However, I am facing an issue where I cannot retrieve the result back from the PHP file even though I echo it in the ajax success function. <script&g ...

I am curious to know why my jQuery when().then() function is firing before the completion of the ajax request in the when clause

I have a situation where I need to set an async callback because a function is fetching content from a remote location. Here's what I am currently doing: $.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(late) { conso ...

The AngularJS error message states that there is an issue because the $resource function is

I am currently facing an issue with my controller, specifically the error message: TypeError: $resource is not a function This error is pointing to the line var Activities = $resource('/api/activities'); app.controller('AddActivityCtrl& ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...

Creating a loading animation that appears when the submit button is pressed in C#

I am working on a MVC website and I thought it would be cool to have a spinning GIF appear when the submit button is clicked until the next view loads. Here is my current code, but unfortunately it's not working and I can't figure out why. <p ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

The collapsed feature of the Bootstrap 4 Navbar is not functioning as

Recently, I delved into the world of Bootstrap 4 and decided to create a collapsing menu. Everything seemed to be working fine when I clicked the button and saw the content display perfectly. However, things took a turn for the worse when I tried to collap ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Extracting information from a hyperlink without the need to actually click on it

Hello, I have recently started learning JavaScript and I am looking to accomplish a specific task. Currently, I am navigating on A.com/. Within the content of A.com/, there is a link labeled as A.com/B. Upon clicking on the link A.com/B, I can see ...