Home > OS >  Clear specific input fields with jQuery
Clear specific input fields with jQuery

Time:06-12

I am trying to clear certain fields in my form.

I have used the following jQuery code, but they do not work for me:

My HTML

<section id="clear-section" >
    <a id="clear-link" href="javascript:void(0)">Clear</a>
</section>

jQuery Code 1

let clearLink = $("#clear-link");
clearLink.on("click", function () {
  $("#calc-form-section-1")
    .find('input[type="text"],input[type="number"]')
    .each(function () {
      $(this).val("");
    });
  });

jQuery Code 2

clearLink.on("click", function () {
    let fieldsArray = [
      totalHomeSqftInput,
      calcRoofSqftInput,
      annualKwInput,
      calcKwInput,
      systemSizeInput,
      roofCompInput,
      pwrWallBattInput,
      totalCostInput,
      roofPriceBeforeItc,
      estTotalBeforeItc,
      estItc,
      pwrWallPriceBeforeItc,
    ];
    
    $.forEach(fieldsArray, function () {
      $(this).trigger("reset");
    });
});

Any help would be greatly appreciated.

Thank you

CodePudding user response:

One approach would be to label the input elements that you wish to clear with a data-clear attribute. You can use a selector to search for these input values and clear them using an each call.

See demo:

$("#clear-link").on("click", function(e) {
  $("#calc-form-section-1 input[data-clear='true']").each(function(i) {
    $(this).val("");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="clear-section" >
  <form id="calc-form-section-1">

    <input type="text" data-clear="true" id="totalHomeSqftInput" value="abc" /><br />
    <input type="text" data-clear="true" id="calcRoofSqftInput" value="abc" /><br />
    <input type="text" data-clear="true" id="annualKwInput" value="abc" /><br />
    <input type="text" data-clear="true" id="calcKwInput" value="abc" /><br />
    <input type="text" data-clear="true" id="systemSizeInput" value="abc" /><br />

    <input type="text" id="other" value="abc" /><br />

    <a id="clear-link" href="javascript:void(0)">Clear</a>
  </form>
</section>

  • Related