1

In my form, there are several input fields which are generated dynamically. I am trying to add a reset button in my form which could clear the input fields. I have added a same class to all those input fields which I want to clear. The class name is "reset". On the time of loading, my form loads and stores some data in the dropdown box. This data is essential for the working of form. I am just trying to clear the data entered in input fields.

I tried few examples available on Google to solve my problem. But unfortunately, none helped me. All I could do is that I have added a reset button in my form with id "reset", which will be used to empty input fields. I need a function to make it work. Can someone please help me....

here is my code

let headings = []

// appending the created HTML string to the DOM
function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
}

// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input type="number" id="${heading}" class="reset">`
      html += '<br>'
    }
  })

  return html
}

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 1,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
     $('#' +   heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using
      
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});



// code to set default values if user enters zero or negative values

 /*    
    function calculate() { 
setTimeout(function(){
const defaults = {PE: 100, ROCE: 60, SG: 1, DY: 1};
 const values = {}; Object.keys(defaults).forEach(id => {
const el = document.getElementById(id); if (el.value < 0) {
 el.value = defaults[id]; 
} 
values[id] = el.value; 
}); 
*/  


//calculation for Rating value

$(document).ready(function(){ 
$("#Cal").click(function(){

var peVal=0,roceVal=0,sgVal=0,dyVal=0,psVal=0,pbVal=0,npmlqVal=0,roaVal=0,deVal=0,upsVal=0,crVal=0
;

jQuery(".fields input").each(function (){ 
var idHeading=$(this).attr("id");  

if(idHeading=="PE"){ peVal=parseInt($(this).val()); } 
if(idHeading=="ROCE"){ roceVal=parseInt($(this).val()); } 
if(idHeading=="SG"){ sgVal=parseInt($(this).val()); } 
if(idHeading=="DY"){ dyVal=parseFloat($(this).val()); } 
if(idHeading=="PS"){ psVal=parseFloat($(this).val()); }
if(idHeading=="PB"){ pbVal=parseFloat($(this).val()); }
if(idHeading=="NPMLQ"){ npmlqVal=parseFloat($(this).val()); }

if(idHeading=="ROA"){ roaVal=parseFloat($(this).val()); }
if(idHeading=="DE"){ deVal=parseFloat($(this).val()); }
if(idHeading=="UPS"){ upsVal=parseFloat($(this).val()); }
if(idHeading=="CR"){ crVal=parseFloat($(this).val()); }


}); 

var output=peVal+roceVal+sgVal+dyVal+psVal+pbVal+npmlqVal+roaVal+deVal+upsVal+crVal
;

$("output[name='amount']").text(output);
 }); 
 });
<html>
    <head>
        <title>Page Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    </head>
    <body>
        
<div class="ui-widget">
  <form id="frm1">
    <label for="company">Drop Down box: </label>
    <input id="company" class="reset"><br /><br />
    
    <div class="fields"></div>
    <!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
 <button  type="button" id="Cal" disabled="disabled">
 Button
 </button>
  <button type="button" id="reset" >Reset</button>
<p> <output name="amount" for="calculation">0</output>
</p>
</form>
    </body>
</html>

5
  • what you want to clear, dynamic input elements or dynamic generated input element's value ? Commented Sep 1, 2019 at 15:42
  • 2
    For your next question... You're supposed to break down the problem into a minimal reproducible example. 90% of your snippet is unrelated to the problem and should have been removed. Commented Sep 1, 2019 at 15:53
  • i was trying to clear dynamic input elements. but now i have got the solution. thanks @dupinder for showing your interest in solving my query.... Commented Sep 1, 2019 at 15:58
  • @andreas i just provided this snippet so that it could become easy for the coders to understand what i am discussing. but yes, next time i would try to provide more minimal snippet... Commented Sep 1, 2019 at 16:04
  • Assuming you want to clear all input elements in the form, just use $('form').trigger('reset'); Commented Sep 1, 2019 at 16:09

3 Answers 3

5

Append this event listener

$("#reset").on('click', function () {
  $('.reset').val('');
});

let headings = []

// appending the created HTML string to the DOM
function initInputs(headingList) {      jQuery(".fields").append(createInputsHTML(headingList))
}

// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input type="number" id="${heading}" class="reset">`
      html += '<br>'
    }
  })

  return html
}

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function (data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({
          ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function () {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function (request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 1,
    source: lists,
    focus: function (event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function (event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using

      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});

// code to set default values if user enters zero or negative values

/*    
   function calculate() { 
setTimeout(function(){
const defaults = {PE: 100, ROCE: 60, SG: 1, DY: 1};
const values = {}; Object.keys(defaults).forEach(id => {
const el = document.getElementById(id); if (el.value < 0) {
el.value = defaults[id]; 
} 
values[id] = el.value; 
}); 
*/


//calculation for Rating value

$(document).ready(function () {
  $("#Cal").click(function () {

    var peVal = 0, roceVal = 0, sgVal = 0, dyVal = 0, psVal = 0, pbVal = 0, npmlqVal = 0, roaVal = 0, deVal = 0, upsVal = 0, crVal = 0;

    jQuery(".fields input").each(function () {
      var idHeading = $(this).attr("id");

      if (idHeading == "PE") { peVal = parseInt($(this).val()); }
      if (idHeading == "ROCE") { roceVal = parseInt($(this).val()); }
      if (idHeading == "SG") { sgVal = parseInt($(this).val()); }
      if (idHeading == "DY") { dyVal = parseFloat($(this).val()); }
      if (idHeading == "PS") { psVal = parseFloat($(this).val()); }
      if (idHeading == "PB") { pbVal = parseFloat($(this).val()); }
      if (idHeading == "NPMLQ") { npmlqVal = parseFloat($(this).val()); }

      if (idHeading == "ROA") { roaVal = parseFloat($(this).val()); }
      if (idHeading == "DE") { deVal = parseFloat($(this).val()); }
      if (idHeading == "UPS") { upsVal = parseFloat($(this).val()); }
      if (idHeading == "CR") { crVal = parseFloat($(this).val()); }

    });

    var output = peVal + roceVal + sgVal + dyVal + psVal + pbVal + npmlqVal + roaVal + deVal + upsVal + crVal;

    $("output[name='amount']").text(output);
  });
});


//reset form fields

$(document).ready(function () {
  $("#reset").on('click', function () {
    $('.reset').val('');
  });
});
<html>
    <head>
        <title>Page Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    </head>
    <body>
        
<div class="ui-widget">
  <form id="frm1">
    <label for="company">Drop Down box: </label>
    <input id="company" class="reset"><br /><br />
    
    <div class="fields"></div>
    <!-- PLEASE NOTE THAT THE OTHER INPUT FIELDS WILL BE ADDED DYNAMICALLY -->
 <button  type="button" id="Cal" disabled="disabled">
 Button
 </button>
  <button type="button" id="reset" >Reset</button>
<p> <output name="amount" for="calculation">0</output>
</p>
</form>
    </body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

This is a good methods:

(function() {
$('#reset').click(function() {
    $(':input','#myform')
        .not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
});
})

or:

$(document).ready(function(){
$(".reset").click(function(){
    $("#Form1").trigger("reset");
});
});

Comments

-1

If you want to clear all the input with class reset

$(document).ready(function() {

  $("#reset").click(function(){
    $('INPUT[class=reset]').each(function(){
         console.log($(this).val());
         $(this).val('');
    });
  });

});

Tested here

2 Comments

friend i want to clear dropdown field also. but your code is not clearing it. thanks in advance.
Thanks friend for your solution. It helped me to know the other possible solutions of my query. Again Thanks @dotnetboss

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.