簡體   English   中英

如何使用按鈕清除動態生成的輸入字段?

[英]How to clear dynamically generated input fields using a button?

在我的表單中,有幾個輸入字段是動態生成的。 我正在嘗試在表單中添加一個重置按鈕,以清除輸入字段。 我向所有要清除的輸入字段添加了相同的類。 類名是“重置”。 在加載時,我的表單會加載一些數據並將其存儲在下拉框中。 此數據對於表格的工作至關重要。 我只是想清除輸入字段中輸入的數據。

我嘗試了一些Google上可用的示例來解決我的問題。 但不幸的是,沒有人幫助我。 我所能做的就是在表單中添加一個ID為“ reset”的重置按鈕,該按鈕將用於清空輸入字段。 我需要一個功能使其起作用。 有人可以幫幫我嗎....

這是我的代碼

 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> 

附加此事件監聽器

$("#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> 

這是一個好方法:

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

要么:

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

如果要清除所有輸入並重置

$(document).ready(function() {

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

});

在這里測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM