0
我輸入了[type = text],其中用戶只能輸入alpha,空格和逗號。 我需要在「輸入」js中的每個逗號後放置一個空格。 任何想法?當用戶輸入到輸入中時符號後的自動空間
我輸入了[type = text],其中用戶只能輸入alpha,空格和逗號。 我需要在「輸入」js中的每個逗號後放置一個空格。 任何想法?當用戶輸入到輸入中時符號後的自動空間
例如使用jQuery:
$("#landing-search-input").keyup(function(event) {
if (event.keyCode == 188) {
$(this).val($(this).val() + " ");
}
});
或
$("#landing-search-input").keyup(function(event) {
var inputValue = $(this).val();
if (inputValue.substr(-1) == ",") {
$(this).val(inputValue + " ");
}
});
如果你想這樣做正確,這樣
後面的空格之後......你需要像下面這樣,這將在所有主要的瀏覽器,包括IE 6
代碼:
function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range;
if (typeof el.selectionStart != "undefined"
&& typeof el.selectionEnd != "undefined") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (typeof document.selection != "undefined"
&& typeof document.selection.createRange != "undefined") {
el.focus();
range = document.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}
document.getElementById("some_input").onkeypress = function(evt) {
evt = evt || window.event;
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
if (String.fromCharCode(charCode) == ",") {
insertTextAtCursor(this, ", ");
return false;
}
};
當插入符號不在輸入文本的末尾時,這將不起作用。 – 2012-03-21 09:24:20