首页 \ 问答 \ 需要从textarea获取更新值(Need to get updated value from a textarea)

需要从textarea获取更新值(Need to get updated value from a textarea)

我有一个textarea,我在其中插入从自动填充字段中选择的值,我想要做的是从textarea获取更新的值。

假设我在textarea中输入三个字符a,b和c我删除了字符c。 我遇到的问题是 - >再次当我从自动填充字段中选择一个字符时,所选字符未显示在textarea中,

该字符确实被添加到内存中,即html代码。 但不会出现在textarea。 下面是html

<div id="secondary" style="min-width:100px; min-height: 10px; float:left">write any character from a to f
    <br/>
    <label for="somechar"></label>
    <input id="somechar" size="22">
    <br>
    <textarea id="some-log" class="log" class="ui-widget-content"></textarea>
</div>

这是Jquery和javascript代码

var secondary = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f"];

下面的函数在textarea中记录消息。 这是我需要更新值的地方。 我不知道如何使用var thought= $("textarea#some-log").val(); 在这里

function some_log(thought) {
    $("#some-log").append(thought+ ", ").prependTo("#some-log");
}

$("#somechar") /* this function is required when selecting multiple values */
.bind("keydown", function (event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
        event.preventDefault();
    }
})

这是Jquery自动完成

    .autocomplete({
    minLength: 0,
    source: function (request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
        secondary, extractLast(request.term)));
    },
    focus: function () {
        // prevent value inserted on focus
        return false;
    },
    select: function (event, ui) {

        some_log(ui.item ? 
                          ui.item.value :
            "Nothing selected, input was " + this.value);

        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");
        return false;
    }
});

http://jsfiddle.net/pratik24/MMpDv/


I have a textarea in which I am inserting values selected from the autocomplete field, What I want to do is get the updated value from the textarea.

supposing I enter three characters a, b and c in the textarea I delete character c. The problem I have is-> again when I select a character from the autocomplete field the character selected does not show up in the textarea,

The character does get added to the memory i.e. the html code. But does not show up in the textarea. Below is the html

<div id="secondary" style="min-width:100px; min-height: 10px; float:left">write any character from a to f
    <br/>
    <label for="somechar"></label>
    <input id="somechar" size="22">
    <br>
    <textarea id="some-log" class="log" class="ui-widget-content"></textarea>
</div>

Here is the Jquery and javascript code

var secondary = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f"];

the function below logs the message in the textarea. here is where i need the updated value. I dont know how i can use some thing like var thought= $("textarea#some-log").val(); over here

function some_log(thought) {
    $("#some-log").append(thought+ ", ").prependTo("#some-log");
}

$("#somechar") /* this function is required when selecting multiple values */
.bind("keydown", function (event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
        event.preventDefault();
    }
})

This is Jquery autocomplete

    .autocomplete({
    minLength: 0,
    source: function (request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
        secondary, extractLast(request.term)));
    },
    focus: function () {
        // prevent value inserted on focus
        return false;
    },
    select: function (event, ui) {

        some_log(ui.item ? 
                          ui.item.value :
            "Nothing selected, input was " + this.value);

        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");
        return false;
    }
});

http://jsfiddle.net/pratik24/MMpDv/


原文:https://stackoverflow.com/questions/16818158
更新时间:2022-03-31 14:03

最满意答案

这是我在上一个问题中使用的代码,减去评论:

$(function() {
    $('#add_customer_form').submit(function() {
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var method = $(this).attr('method');
        $.ajax({
            url: url,
            type: method,
            data: data,
            dataType: 'json',
            success: function(data) {
                var $div = $('<div>').attr('id', 'message').html(data.message);
                if(data.success == 0) {
                    $div.addClass('error');
                } else {
                    $div.addClass('success');
                }
                $('body').append($div);
            }
        });
        return false;
    });
});

如果我是对的,你基本上要问的是如何使这段代码适用于多个表单,而无需编辑选择器。 这很容易。 只要您在包含表单的每个页面中都包含上述代码,就可以将$('#add_customer_form')部分更改$('form.json_response') 。 有了这个选择器,我们基本上告诉jQuery“任何带有json_response类的json_response都应该通过这个提交函数来处理” - 我正在使用的特定类在这里不相关,重点是你使用一个类并将它交给所有的应具有该功能的表单。 请记住,jQuery适用于对象 。 我最初拥有它的方式恰好是1个元素,但是每个jQuery函数都意味着对匹配的元素进行操作。 这样,无论何时创建要通过AJAX处理的表单(并且您知道服务器将返回带有成功指示符的JSON响应),您只需添加您选择的任何类,jQuery代码将接管并处理它您。

还有一个更干净的插件可以做到这一点,但上面也很好。


Here is the code I used in the last question, minus the comments:

$(function() {
    $('#add_customer_form').submit(function() {
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var method = $(this).attr('method');
        $.ajax({
            url: url,
            type: method,
            data: data,
            dataType: 'json',
            success: function(data) {
                var $div = $('<div>').attr('id', 'message').html(data.message);
                if(data.success == 0) {
                    $div.addClass('error');
                } else {
                    $div.addClass('success');
                }
                $('body').append($div);
            }
        });
        return false;
    });
});

If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.

There is also a cleaner plugin that sort of does this, but the above is fine too.

相关问答

更多
  • 你已经定义了一个局部变量json来掩饰引用JSON模块的全局符号json 。 重命名你的本地变量应该允许你的代码工作。 You've defined a local variable json that masks the global symbol json referring to the JSON module. Renaming your local variable should allow your code to work.
  • 你的问题的答案是在堆栈跟踪。 “JsonRequestBehavior to AllowGet” 所以在你的控制器中使用它: return Json(data, JsonRequestBehavior.AllowGet) Answer for your question was in the stack trace. "JsonRequestBehavior to AllowGet" So use it in your Controller as: return Json(data, JsonReques ...
  • 该响应是XML( application/xml ),而不是JSON( application/json )。 That response is XML (application/xml), not JSON (application/json).
  • 我认为你需要用下面的代码替换一些代码, if let json: NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary { let responseString = NSString(data: data!, encoding: NSU ...
  • 这是我在上一个问题中使用的代码,减去评论: $(function() { $('#add_customer_form').submit(function() { var data = $(this).serialize(); var url = $(this).attr('action'); var method = $(this).attr('method'); $.ajax({ url: url, ...
  • 您可以像这样输入要添加的类: if (json['error']['firstname']) { var $input = $('#shipping-address input[name="firstname"]'); $input.addClass('someClass').after('' + json['error']['firstname'] + ''); } 如果填写了字段,则删除(样式类和span类) $('input[na ...
  • SQL Server中的JSON仅在版本2016和更高版本中受支持。 您的安装是2014年安装,因此它不起作用。 您可以将安装升级到SQL Server 2016或查找其他人编写的自定义JSON解决方案/功能/特效。 JSON in SQL Server is only supported in versions 2016 and later. Your installation is a 2014 install so it will not work. You can either upgrade yo ...
  • 只需实现json.Marshaler接口: func main() { var err error = JsonErr{errors.New("expected")} json.NewEncoder(os.Stdout).Encode(err) } type JsonErr struct { error } func (t JsonErr) MarshalJSON() ([]byte, error) { return []byte(`{"error": "` + t.Er ...
  • 您的问题与此类似如何解析会导致非法C#标识符的JSON字符串? 所以,你的模型应该是 public class Variant { public string Name { get; set; } public string Found { get; set; } } public class RootObject { public Dictionary stats { get; set; } public string response ...
  • 干得好: var root = JsonConvert.DeserializeObject(json); var userItem = root.results.items .Select(i => new UserItem { id = i.id, na ...

相关文章

更多

最新问答

更多
  • python的访问器方法有哪些
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。
  • 响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)
  • 在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)
  • NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)
  • 元素上的盒子阴影行为(box-shadow behaviour on elements)
  • Laravel检查是否存在记录(Laravel Checking If a Record Exists)
  • 设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)
  • 想学Linux 运维 深圳有哪个培训机构好一点
  • 为什么有时不需要在lambda中捕获一个常量变量?(Why is a const variable sometimes not required to be captured in a lambda?)
  • 在Framework 3.5中使用服务器标签<%=%>设置Visible属性(Set Visible property with server tag <%= %> in Framework 3.5)
  • AdoNetAppender中的log4net连接类型无效(log4net connection type invalid in AdoNetAppender)
  • 错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)
  • 等待EC2实例重启(Wait for an EC2 instance to reboot)
  • 如何在红宝石中使用正则表达式?(How to do this in regex in ruby?)
  • 使用鼠标在OpenGL GLUT中绘制多边形(Draw a polygon in OpenGL GLUT with mouse)
  • 江民杀毒软件的KSysnon.sys模块是什么东西?
  • 处理器在传递到add_xpath()或add_value()时调用了什么顺序?(What order are processors called when passed into add_xpath() or add_value()?)
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • SQL查询,其中字段不包含$ x(SQL Query Where Field DOES NOT Contain $x)
  • PerSession与PerCall(PerSession vs. PerCall)
  • C#:有两个构造函数的对象:如何限制哪些属性设置在一起?(C#: Object having two constructors: how to limit which properties are set together?)
  • 平衡一个精灵(Balancing a sprite)
  • n2cms Asp.net在“文件”菜单上给出错误(文件管理器)(n2cms Asp.net give error on Files menu (File Manager))
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的