在文本区域插入json对象

Insert json object in text area

本文关键字:json 对象 插入 区域 文本      更新时间:2023-09-26

你好,我正在用JSP开发一个小应用程序。

我的想法是在用户在文本区域输入时给出一个JSON元素的引用。

例如

:如果JSON包含:

二氧化碳,水,c9O

,在文本区域,用户正在输入一个句子,一旦用户输入一个特殊字符,如@或'或/如果他/她写了"c"字符,我想要一个小下拉显示以c开头的两个元素。用户可以选择元素之后,然后当表单发布时,我想提取那些从JSON中输入的信息。

我猜这就像你开始在Facebook上输入名字一样。

任何想法?提前感谢

EDIT: JS Fiddle

<form action="./Protocol" method="POST">
    <textarea rows=5 cols=50></textarea>
   <input type="submit"/></form>


$('textarea').textcomplete([{
match: /(^|'s)('w{2,})$/,
search: function (term, callback) {
    var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo'];
    callback($.map(words, function (word) {
        return word.indexOf(term) === 0 ? word : null;
    }));
},
replace: function (word) {
    return word + ' ';
}}]);

上面的JS Fiddle做了我想要的部分。

我想在这里完成的两件事之一
1. 如果在JSON中,每个单词都有一个ID,比如{"ID": "1","name": "GOOGLE"}我能得到表单发布时textarea中要发布的ID
2. 或者只是数组索引号,我如何将表单中的值与textarea分开POST

好吧,不管我说了什么,这里有一个基本的例子,教你如何实现这一点(因为我很无聊,但不是很无聊,我要为你做的:)):

HTML

<input id="input"/>
<div id="dropdown"></div>

JS

// grab the DOM elements
var input = document.getElementById('input');
var dropdown = document.getElementById('dropdown');
// assign an function to the onkeyup event for your input box
input.onkeyup = search;
// define your data structure
var arr = ['cO2', 'H2O', 'c9O'];
function search() {
  // get the content and length of the content
  // `this` in this instance refers to the element to which
  // we assigned the function
  var val = this.value;
  var len = val.length;
  // filter out the elements from the array that match
  // the content, or nothing if the input is empty
  dropdown.textContent = arr.filter(function(el) {
    return val !=='' ? el.substring(0, len) === val : '';
  });
}

演示

希望能帮到你。