I am using a dialog with a textarea. Upon clicking the ok-button the textarea's value gets sent to a server via ajax.
The first time the user writes to the textarea the value gets read correctly, but upon all subsequent actions the value being sent is the same as the first time as if the user had entered the same string over and over again.function message(url) {
var mydiv;
mydiv = $(document.createElement('div'));
mydiv.html("enter message: <textarea name='message' id='message'/>");
mydiv.d开发者_开发知识库ialog(setProps(url));
mydiv.dialog('open');
}
function setProps(url) {
return {
buttons: {
"ok": function() {
$.get('/act?url=' + url + '&message=' + $("#message").val().trim(),
function(data) {
$("#content").load('/react?url=' + url);
}
);
$(this).dialog("close");
$(this).dialog("destroy");
// If I use the following all subseq. actions are empty:
// $("#message").val('');
}
}
}
}
When you create a dialog it gets appending at the end of the <body>
, just because you're destroying the dialog doesn't mean the elements in it go away, they're just returned to their location, or in this case still at the end of the <body>
, you also need to .remove()
those elements, like this:
$(this).dialog("destroy").remove();
Otherwise (currently) you're adding a new #message
element each time, and what you're seeing is a classic duplicate ID issue, it's getting the value of the first one (the first you appended...that never left).
Overall there are a few more issues, for example IE<9 not having String.prototype.trim()
so your value would blow up, as would having anything like &
in it. Let jQuery encode your values, like this:
function message(url) {
$("<div>enter message: <textarea name='message' id='message'></textarea></div>")
.dialog(setProps(url));
}
function setProps(url) {
return {
buttons: {
"ok": function() {
$.get('/act', { url: url, message: $.trim($("#message").val()) },
function(data) {
$("#content").load('/react?url=' + url);
}
);
$(this).dialog("destroy").remove();
}
}
}
}
精彩评论