Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear button does not work.

Here is what I have attempted so far:

// JavaScript code for adding and removing input elements
var counter = 1,
  custom = $('#custom');
$(function() {
  $('#add_field').click(function() {
    counter += 1;
    var newRow = $('<div class="row' + counter + '"><span class="wrap_input"><input id="exception_' + counter + '" name="" type="text"><button class="btn_clear">clear</button><button class="remove-text-box">Remove</button></span></div>');
    custom.append(newRow);
    (function(index) {
      newRow.find('.remove-text-box').click(function() {
        custom.find('.row' + index).remove();
      });
    })(counter);
  });
});

// JavaScript code for clearing input value 
$('.wrap_input').each(function() {
var $inp = $(this).find("input"),
      $cle = $(this).find(".btn_clear");
$inp.on("input", function(){
  $cle.toggle(!!this.value);
  });
$cle.on("touchstart click", function(e) {
  e.preventDefault();
    $inp.val("").trigger("input").focus();
    $inp.change();
  });
});
.btn_clear { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field" href="#">add input</button>

<div id="custom">
  
  <span class="wrap_input">
    <input type="text" value="">
    <button class="btn_clear">clear</button>
  </span>

</div>

The first input is functioning correctly, however, after adding another input element, the clear button does not appear.

Please assist me in resolving this issue.

Answer №1

Utilize the .on method as illustrated below. The newly added elements are not being properly connected with the required functions.

Revised function

$(document).on("input", "input", function() {
  $(this).next(".btn_clear").toggle(!!this.value);
});
$(document).on("touchstart click", ".btn_clear", function(e) {
  e.preventDefault();
  $(this).prev("input").val("").trigger("input").focus();
});

// Add or remove input fields
var counter = 1,
  custom = $('#custom');
$(function() {
  $('#add_field').click(function() {
    counter += 1;
    var newRow = $('<div class="row' + counter + '"><span class="wrap_input"><input id="exception_' + counter + '" name="" type="text"><button class="btn_clear">clear</button><button class="remove-text-box">Remove</button></span></div>');
    custom.append(newRow);
    (function(index) {
      newRow.find('.remove-text-box').click(function() {
        custom.find('.row' + index).remove();
      });
    })(counter);
  });
});

// Clear input field value 

$(document).on("input", "input", function() {
  $(this).next(".btn_clear").toggle(!!this.value);
});
$(document).on("touchstart click", ".btn_clear", function(e) {
  e.preventDefault();
  $(this).prev("input").val("").trigger("input").focus();
});
.btn_clear {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field" href="#">add input</button>


<div id="custom">
  <span class="wrap_input">
    <input type="text" value="">
    <button class="btn_clear">clear</button>
  </span>
</div>

Answer №2

Here is a code snippet that can be helpful:

// Function to manage input fields
var counter = 1,
    custom = $('#custom');
$(function() {
    $('#add_field').click(function() {
        counter += 1;
        var newRow = $('<div class="row' + counter + '"><span class="wrap_input"><input id="exception_' + counter + '" name="" type="text"><button class="btn_clear">clear</button><button class="remove-text-box">Remove</button></span></div>');
        custom.append(newRow);
        (function(index) {
            newRow.find('.remove-text-box').click(function() {
                custom.find('.row' + index).remove();
            });
        })(counter);

        // Call clearInputValue function after row creation
        setTimeout(function() {
            clearInputValue();
        }, 0);
    });
});

// Function to clear input value
function clearInputValue() {
    $('.wrap_input').each(function() {
        var $inp = $(this).find("input"),
            $cle = $(this).find(".btn_clear");
        $inp.on("input", function() {
            $cle.toggle(!!this.value);
        });
        $cle.on("touchstart click", function(e) {
            e.preventDefault();
            $inp.val("").trigger("input").focus();
            $inp.change();
        });
    });
}

Answer №3

Here is a demonstration of how this can be achieved.

    function add(){
      //Add
      $(".elements" )
        .append( "<div>\
        <input type='text' class='myinput'>\
        <button class='clear'>clear</button>\
        <button class='remove'>remove</button>\
        </div>" );
       
      init()
      
    }

    function init(){ 
      //Remove
      var x = document.getElementsByClassName('remove')
      for(var i = 0; i< x.length; i++){
          x[i].addEventListener("click", function(e){
            e.target.parentNode.remove()
          })
      }
      
      //Clear
      var y = document.getElementsByClassName('clear')
      for(var i = 0; i< y.length; i++){
          y[i].addEventListener("click", function(e){  
            e.target .parentNode.querySelector("input").value = ''; 
            //after clear hide .clear button 
            e.target.parentNode.querySelector(".clear").style.display = "none";
          })
      }
      
      //Show hide .clear button 
      var z = document.getElementsByClassName('myinput')
      for(var i = 0; i< z.length; i++){
         z[i].addEventListener("input", function(e){    
            if(e.target.value.length > 0){
              e.target.parentNode.querySelector(".clear").style.display = "inline";
            }else{
              e.target.parentNode.querySelector(".clear").style.display = "none";
            }
         })
      }
      
    }

    init();
  .clear{ 
      display:none;
    }
    <script src="https://code.jquery.com/jquery-1.6.4.js"></script>
    <div class="elements">
      <button id="add" onclick="add()">Add</button>
      <div>
        <input class="myinput">
        <button class="clear">clear</button>
      </div> 
     </div>

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 Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

View cards from a restricted Trello board without requiring visitors to have a Trello account or to authorize through a popup

I have a company with ongoing projects listed on a private Trello board. We are interested in showcasing these projects on our website in real-time by connecting to the board. After implementing this example, I can successfully retrieve and display the ca ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

HTML: Learn how to concatenate the href attribute of an anchor tag instead of replacing it

I am currently on the page www.myUniqueWebsite.com/sign-up?type=explore In the navigation menu, there is a link to switch languages. <a href="?lang=es">Spanish</a> When I click on this link, it redirects me to www.myUniqueWebsite.com/ ...

What's causing this sluggish performance?

I'm in the process of developing a Google Chrome extension and I can't help but wonder why window.onload = loadPage; function loadPage() { document.getElementById('nav-robux-amount').innerHTML = '0'; console.log(" ...

There is a syntax error in the for-loop within the AngularJS $http.get causing an unexpected identifier

I'm encountering a 'syntax error: unexpected identifier' and my browser seems to be getting stuck in a loop after executing this code. I figured incorporating setInterval for delaying API requests was a sound strategy according to the API re ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

The app.use function encountered an error stating "Cannot modify header information - headers already sent"

Within my app.js file, I have the following code snippet: app.use(function(req, res, next){ if(!req.user){ res.redirect('/login_'); } next(); }) Upon reviewing the above code, everything appears to be correct. In my route/index.js fi ...

Display the same DIV element across various HTML tabs

When two different tabs are clicked, I need to display a set of 10 Search Fields. Both tabs have the same fields, so instead of using separate DIVs, I want to use the same DIV and only change the AJAX REST End-Point based on the selected TAB. Can someone ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

The CSS hamburger icon displayed in the browser features three bars of varying heights

Looking to create a hamburger icon menu using only CSS? Check out my implementation below which includes three span tags in the HTML document. .sidebar-toggle { display: inline-block; } .sidebar-toggle span { display: block; width: 1.5rem; heig ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

Uploading files in chunks using a combination of HTML, JavaScript,

I've been using a file chunking solution (although I can't recall its origin), but I've made some modifications to suit my requirements. Most of the time, the file uploads successfully; however, there are instances where an error occurs. U ...

Tips for incorporating routes in Polka.js in a way that resembles the functionality of express.Route()

One of the challenges I am facing is trying to import route logic from another file in my project. While using Express.js, this could be done easily with express.Route(). However, when attempting polka.Route(), an error occurs stating that Route doesn&apos ...

Guide to sending a response to an AJAX post request in Express with Node.js: Answered

For a project focused on practicing Node.js and jQuery Ajax, I'm working on a simple task. Essentially, I have an ajax post request that sends data to a Node.js server and waits for a response. On the server-side, there's code that processes this ...

Tips for making your inner content as wide as possible

I'm currently working on developing collapsible tables, where an outer and inner table are displayed for every row that is clicked. This is the code I have implemented: HTML: <table class="table outerTbl mb-0"> <thead> <t ...

Separate each element with a time gap when using the .each() function in

Below is the code snippet that I have: $('.action-button').each(function(i, obj) { $(obj).trigger('click') }); I am looking to introduce a delay between each iteration of the loop, ideally a 5-second delay. Is it achievable through se ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...