Как очистить сообщение в текстовой области с помощью jquery?
- ОБНОВЛЕНО -
Я хочу очистить сообщение в текстовом поле в обратном вызове.
Может ли кто-нибудь сказать мне, как его удалить?
Я попробовал $( "# message" ). empty(), но он не пуст.
Спасибо заранее.
<form method="post" id="form" action="index.php/admin/messages/insertShoutBox">
<input name="user" id="nick" value="admin" type="hidden">
<p class="messagelabel"><label class="messagelabel">Message</label>
<textarea id="message" name="message" rows="2" cols="40"></textarea>
<input disabled="disabled" id="send" value="Sending..." type="submit"></p>
</form>
Полный код
$("#form").submit(function(){
if(checkForm()){
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "index.php/admin/dashboard/insertShoutBox",
data: $('#form').serialize(),
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
$('#message').val('').empty();
//reactivate the send button
$("#send").attr({ disabled:false, value:"SUBMIT !" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
Ответы
Ответ 1
$('#message').val('');
Объяснение (из @BalusC):
textarea
- это элемент input
со значением. Вы действительно хотите "опорочить" значение. Так как для любого другого элемента input
(input
, select
, textarea
) вам нужно использовать element.val('');
.
Также см. docs
Ответ 2
$('#message').html('');
Вы также можете использовать этот метод. Поскольку все между тегом open и close textarea является html-кодом.
Ответ 3
.html( ''). был единственным методом, который решил это для меня.
Ответ 4
//, поскольку вы используете AJAX, я считаю, что вы не можете полагаться на это с помощью submit
// опуская действие, вы можете включить charset utf-8, поскольку метод POST JQuery использует это также, я думаю,
HTML
<input name="user" id="nick" value="admin" type="hidden">
<p class="messagelabel"><label class="messagelabel">Message</label>
<textarea id="message" name="message" rows="2" cols="40"></textarea>
<input disabled="disabled" id="send" value="Sending..." type="submit">
Javacript
//reset the form to it original state
$.fn.reset = function () {
$(this).each (function() {
this.reset();
});
//any logic that you want to add besides the regular javascript reset
/*$("select#select2").multiselect('refresh');
$("select").multiselect('destroy');
redo();
*/
}
//start of jquery based function
jQuery(function($)
{
//useful variable definitions
var page_action = 'index.php/admin/messages/insertShoutBox';
var the_form_click=$("#form input[type='submit']");
//useful in case that we want to make reference to it and update
var just_the_form=$('#form');
//bind to the events instead of the submit action
the_form_click.on('click keypress', function(event){
//исходный код, удалил обработчик события отправки.
// $( "# форма" ). представить (функция() {
if(checkForm()){
//var nick = inputUser.attr("value");
//var message = inputMessage.attr("value");
//seems more adequate for your form, not tested
var nick = $('#form input[type="text"]:first').attr('value');
var message = $('#form input[type="textarea"]').attr('value');
//we deactivate submit button while sending
//$("#send").attr({ disabled:true, value:"Sending..." });
//This is more convenient here, we remove the attribute disabled for the submit button and we change it value
the_form_click.removeAttr('disabled')
//.val("Sending...");
//not sure why this is here so lonely, when it the same element.. instead trigger it to avoid any issues later
.val("Sending...").trigger('blur');
//$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST",
//see you were calling it at the form, on submit, but it here where you update the url
//url: "index.php/admin/dashboard/insertShoutBox",
url: page_action,
//data: $('#form').serialize(),
//Serialize the form data
data: just_the_form.serialize(),
// complete: function(data){
//on complete we should just instead use console log, but I;m using alert to test
complete: function(data){
alert('Hurray on Complete triggered with AJAX here');
},
success: function(data){
messageList.html(data.responseText);
updateShoutbox();
var timeset='750';
setTimeout(" just_the_form.reset(); ",timeset);
//reset the form once again, the send button will return to disable false, and value will be submit
//$('#message').val('').empty();
//maybe you want to reset the form instead????
//reactivate the send button
//$("#send").attr({ disabled:false, value:"SUBMIT !" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
//return false;
//we prevented it by removing the action at the form and adding return false there instead
event.preventDefault();
}); //end of function
}); //end jQuery function
</script>
Ответ 5
Комментарий к jarijira
Ну, у меня было много проблем с методами .html и .empty() для ввода o. Если идентификатор представляет собой вход, а не другой тип селектора html, например
или использовать функцию .val() для управления.
Например: это правильный способ управления входными значениями
<textarea class="form-control" id="someInput"></textarea>
$(document).ready(function () {
var newVal='test'
$('#someInput').val('') //clear input value
$('#someInput').val(newVal) //override w/ the new value
$('#someInput').val('test2)
newVal= $('#someInput').val(newVal) //get input value
}
Для ненадлежащего, но иногда работает
Например: это правильный способ управления входными значениями
<textarea class="form-control" id="someInput"></textarea>
$(document).ready(function () {
var newVal='test'
$('#someInput').html('') //clear input value
$('#someInput').empty() //clear html inside of the id
$('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input.
newVal= $('#someInput').val(newVal) //get input value
}
Проблема, с которой я столкнулся, заключалась в использовании метода $getJson, и я действительно мог использовать вызовы .html для управления моими входами. Однако всякий раз, когда у меня была ошибка или ошибка на getJSON, я больше не мог изменять свои входы с помощью вызовов .clear и .html. Я все еще мог вернуть .val(). После некоторых экспериментов и исследований я обнаружил, что вы должны использовать функцию .val() для внесения изменений в поля ввода.
Ответ 6
для установки пустых всех входных данных, таких как текстовое поле выберите и введите следующий код:
$('#message').val('').change();