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

Tips on effectively managing sibling nodes with unique behavior on the initial one

Greetings and thank you for taking the time to read and assist. While I have gained a good understanding of how XSLT 1.0 processes XML, there is one issue that continues to baffle me. The problem arises from having a template that matches the first node ...

Issue encountered with the ".replaceWith" method not functioning properly when incorporating the "nl2br()" function and inserting the "Enter" key within database text

I am facing an issue with editing text displayed from the database. When the text is in one line, the "Edit Text" button works perfectly. However, if I use an enter to create a new line in the text, the editing functionality does not work as expected. To ...

Issues with jQuery Relative URLs Not Functioning as Expected

Having trouble with jQuery here. It's behaving oddly - working on one web container but not another. The problem arises when I make an AJAX call to the backend; it fails to construct the correct URI. Interestingly, this issue only occurs on Oracle Web ...

Implementing the functionality to allow users to submit and delete comments using AJAX and PHP

I have implemented a php code to display all comments on any post from my MySQL database. Now, I would like to add a submit button to each comment for users to delete it without having to reload the page. I want to achieve this using AJAX but struggling wi ...

Adjust the width of a div based on its height dimension

I have a div called #slideshow that contains images with a 2:1 aspect ratio. To set the height of the image using jQuery, I use the following function: Keep in mind that the Slideshow Div is always 100% wide in relation to the browser window. If the use ...

Identify the key name in an array of objects and combine the corresponding values

Here is an example of my array structure: array = [{ "name": "obj0_property0", "url": "picture1" }, { "name": "obj1_property0", "url": "picture1" }, { "name": "obj0_property1", "url": "picture2" }] I am looking to transform this array using J ...

Stop the automatic hiding of the sticky header when reaching the bottom of the page

I have implemented the position: sticky property for my website's header. However, I am facing an issue where the header becomes hidden when I scroll halfway down the page (bottom on mobile devices). Can anyone suggest a solution to fix this problem? ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

Vue.js component still not transitioning out despite using mode="out-in"

As I navigate my way through learning about vue.js, one issue that has been puzzling me is how to make routed pages fade in and out when a user switches to a new page. Despite thinking it would be a simple task with vue, I have been struggling quite a bit ...

Is it feasible in Vue to import an scss file with deep selectors into the scoped styles of a component?

Is it possible to extract a Vue component's scoped SCSS with deep selectors into a separate file and then import it back in? For example: // Main.vue <template> <div id="main"> <h1>Title</h1> <span>Text< ...

The Axios GET call encountered an error with a status code of 404

I am currently working on developing a blog/articles application using vue.js. This app utilizes axios to retrieve data from my db.json file by making a get request. The objective is to display the selected article's content when it is clicked on from ...

Generating multiple div elements within an AJAX iteration

Currently, I am retrieving data from the server side using AJAX. My goal is to populate data from a list of objects into divs but I am facing an issue where I cannot create the div while inside the foreach loop. $(document).ready(function () { var ...

Tips for utilizing identical properties across numerous styled elements:

Utilizing the styled-components library, I have enhanced the header components from the Blueprintjs library. The current template for the H6 component appears as follows: export const DH6 = styled(H6)` color: ${(props) => (props.white ? "white&qu ...

Comprehending the inner workings of the reduce() method

After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

Reducing Image Size for Logo Placement in Menu Bar

Hello all, I am a newcomer to the world of web coding. Please bear with me if I ask something that may seem silly or trivial. I recently created a menu bar at the top of my webpage. Below that, there is a Div element containing an image. My goal is to make ...

Exploring how to utilize optional URL parameters within Express.js

When using Express.js version 4.14, I implemented the following route: app.get('/show/:name/:surname?/:address?/:id/:phone?', function(req, res) { res.json({ name: req.params.name, surname: req.params.surname, address ...

receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements. place locfrnd, which is an array While I was able to successfully access place, I encountered an error when trying to a ...

Mastering JQuery: Techniques for Managing Events Across Numerous Elements

My view page utilizes Ajax and JQuery to retrieve data from Codeigniter's controller, then presents it in HTML format. Below is the code for the Ajax post: $(document).ready(function(){ var fileId = 0; var wrapper = $("#preference"); ...

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...