Crazy Developer
Crazy Developer

Reputation: 27

How to clear a input field in jQuery?

How do I clear the input fields "add__description" & "add__value" after clicking the submit button in my Budget App. [In jQuery]

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bottom">
  <div class="add">
    <div class="add__container">
      <select class="add__type">
        <option value="inc" selected>+</option>
        <option value="exp">-</option>
      </select>
      <input type="text" class="add__description" placeholder="Add description">
      <input type="number" class="add__value" placeholder="Value">
      <button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
    </div>
  </div>

I call a clear field function to clear the fields. I tried something like this...

clearFields: function() {
        $(".add__description, .add__value").val("");
    },

Here is the codePen link - CodePen Link

Upvotes: 0

Views: 126

Answers (3)

pid
pid

Reputation: 11607

In the clear function simply do this:

    $(".add__description,.add__value").val("");

You were taking the elements in a wrong way. The class name is sufficient.


EDIT: code pen review

I think what you want to achieve is the fields getting cleared after the entry is added to the Income/Expenses list.

To achieve this you have to move the line

UICtrl.clearFields();

into the eventBtn() method, like this:

function eventBtn() {
    var input = UICtrl.getInp();

    var newItem = budgetCtrl.addItem(input.type, input.des, input.val);

    UICtrl.addListItem(newItem, input.type);
    UICtrl.clearFields();
}

Upvotes: 3

MikeM
MikeM

Reputation: 27415

The jQuery syntax is correct from @pid

You'll also need to include the call to clearFields in your addListItem method

addListItem: function(obj, type) {
    ...
    this.clearFields();
},

https://codepen.io/pxfunc/pen/XoWrzo

Upvotes: 2

jvk
jvk

Reputation: 2211

clearFields: function() {
  $element.click(function (e) {
    $('.add__description, .add__value').val('');
  }
},

$(function(){
  $('button.add__btn').click(function(){
     $('.add__description, .add__value').val('');
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bottom">
  <div class="add">
    <div class="add__container">
      <select class="add__type">
        <option value="inc" selected>+</option>
        <option value="exp">-</option>
      </select>
      <input type="text" class="add__description" placeholder="Add description">
      <input type="number" class="add__value" placeholder="Value">
      <button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
    </div>
  </div>

Upvotes: 0

Related Questions