简体   繁体   中英

How to clear a textarea with jquery?

I have the following:

<div class="tab-pane" id="message">
      <textarea rows="4" cols="50" id="send_message" placeholder="Enter text ...">  </textarea>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">OK</a>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">Cancel</a>

</div>

I want to clear the textarea contents when I click the cancel button. I have:

$('#message').on("click", "a", function(){
    if($(this).is(":contains(Cancel)")) {

      $("#send_message")(
                  function(){
                  $(this).val('');

                }
                );

    } 
    else if($(this).is(":contains(OK)"))  {
                ......
    }
});

but this doesn't do anything. How can I fix this.

You can use this:

$('#message').on("click", "a", function () {
    if ($(this).is(":contains(Cancel)")) {
        $("#send_message").val('');
    } else if ($(this).is(":contains(OK)")) { // other code

    }
});

Demo here

In your code you used the selector $("#send_message") , you cannot just add a function after that way.The $(this) you referred in that "wrong placed" function you already "have" by using the id selector. So I used your idea and corrected some things on your code to make it work.

I think there is a bug in your line. It should just be:

$("#send_message").val("")

Here is a fiddle that does what you need. http://jsfiddle.net/PsWHJ/

<div class="tab-pane" id="message">
      <textarea rows="4" cols="50" id="send_message" placeholder="Enter text ...">  </textarea>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">OK</a>
      <a href="#message" class="btn btn-large btn-info"  data-toggle="tab">Cancel</a>
</div>


$('a','#message').on('click',function(){
    if($(this).text() === 'OK'){
        alert('Process Form');
    }else{
        $('#send_message').val("");
    }
});

There is another way...

$('#message').on("click", "a", function () {
    var jqEl = $(this);
    if (jqEl.text() == "Cancel")) {
        jqEl.prevAll('textarea').val('');
    } else if (jqEl.text() == "OK") { 
         //Do other stuff...
    }
});

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM