我有以下代码:
<script type="text/javascript">
function createDialog(text, id) {
return $("<div class='dialog'><textarea id='textarea' class ='texbox' name='textarea' value='text'>" + text + "</textarea></div>"
.dialog({
dialogClass: "dialogStyle",
title: "Edit Description",
resizable: false,
position: {
my: "right+240 top-200",
at: "center",
of: $("body"),
within: $("body")
},
height: 200,
width: 300,
modal: true,
buttons: {
"Save": function() {
var product = $(this).find('textarea [name="textarea"]').val();
$(this).dialog("close");
$("#" + id).val(product);
},
Cancel: function() {
$(this).dialog("close");
}
},
overlay: {
opacity: 0.5,
background: "black"
}
});
}
</script>
如何在对话框中为textarea添加最多255个字符的字符数? 我已经四处查找代码,但是将它放在函数createDialog中将无法工作,并且获取长度变量在将其放入对话框时也不起作用。
答案 0 :(得分:0)
您可能希望使用委托。你可以这样做:
$(document).on('input propertychange', '#textarea', function() {
var text = $('#textarea').val();
if (text.length > 255) {
$('#textarea').val(text.substring(0,255));
}
//Maybe some code to display a message to the user, or update a character count element or something?
});
答案 1 :(得分:0)
更改对话框以包含计数的DIV:
return $("<div class='dialog'><textarea id='textarea' class ='texbox' name='textarea' value='text'>" + text + "</textarea><div>Characters: <span class='charcount'>0</span></div></div>"
然后添加以下JS:
$(document).on("keyup edit paste", ".dialog .texbox", function(e) {
var charcount = $(this).val().length;
if (charcount > 255) {
e.preventDefault();
return;
}
$(this).closest(".dialog").find(".charcount").text(charcount);
});
function createDialog(text, id) {
return $("<div class='dialog'><textarea id='textarea' class ='texbox' name='textarea' value='text' placeholder='"+text+"'></textarea><div>Characters: <span class='charcount'>0</span></div></div>")
.dialog({
dialogClass: "dialogStyle",
title: "Edit Description",
resizable: false,
position: {
my: "right+240 top-200",
at: "center",
of: $("body"),
within: $("body")
},
height: 200,
width: 300,
modal: true,
buttons: {
"Save": function() {
var product = $(this).find('textarea[name="textarea"]').val();
$(this).dialog("close");
$("#" + id).val(product);
},
Cancel: function() {
$(this).dialog("close");
}
},
overlay: {
opacity: 0.5,
background: "black"
}
});
}
$("#button").click(function() {
createDialog("This is a message", "foo");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<button id="button">Show dialog</button>
<input id="foo"/>
&#13;