简体   繁体   English

如何使用jQuery清除文本区域?

[英]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. 在您的代码中,您使用了选择器$("#send_message") ,您不能再$(this)添加一个function 。通过id选择器,您已经“拥有”了该“错误放置”函数中的$(this) 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/ 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 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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