pauld
pauld

Reputation: 421

How to remove user input from a text input box with Jquery on submit?

I can't seem to get this to work for the life of me. I've tried setting the value to '' with getElementById('guess').value and $('#guess').val, tried using $('#formGuess').reset(), etc. Don't know why the value won't clear out.

Here is my code on this:

js

$('#submit').on('click', function(e) {
  e.preventDefault();

  var guess = $('#guess').val();
  $('#guess').removeAttr('value');
}

HTML

<div class="container center">
      <div class="row">
        <div class="col-md-4 col-md-offset-4">
          <form class="form-horizontal" method="post" id="guessForm">
            <div class="form-group">
              <div>
                <input type="text" class="form-control" placeholder="Guess" id="guess"/>
              </div>
                <input type="submit" class="btn btn-success" name="submit" value="Guess" id="submit"/>
            </div>
          </form>
        </div>
      </div>

Upvotes: 0

Views: 118

Answers (3)

Munawir
Munawir

Reputation: 3356

From your code,

var guess = $('#guess').val();

you are getting the value not setting.

To set the value

$('#guess').val('');

Upvotes: 0

Damian Wojakowski
Damian Wojakowski

Reputation: 857

First, you should attach a "submit" listener to the form, not to the button, e.g.

<form id="someForm"></form>

$("#someForm").submit(function () {
    // your code
});

But if you want to attach it to the button, then you can do that, no worries.

Make sure that the event is called. Are you sure that the function within "click" event is called? Put there a console.log("someText");

If it's called, then make sure that jQuery is getting the right element. Maybe you've made a typo? Maybe there's a missing "#" sign? Or maybe the jQuery is not loaded at all?

Open developers tools and check what's in the console.

Probably you've made a simple mistake - it's always about simple mistakes. : )

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

Set empty string as the value of textbox like following.

$('#guess').val('');

Upvotes: 4

Related Questions