jQuery为动态创建的输入文本字段添加值 [英] jquery add value to dynamically created input text field

查看:90
本文介绍了jQuery为动态创建的输入文本字段添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组通过jQuery ajax创建的动态创建输入文本框,需要用值填充某些字段.我正在使用这个;

I have a set of dynamically create input text boxes created via jQuery ajax and need to populate certain fields with values. I am using this;

$('#priority').attr('value', tplData);

但这似乎不起作用.

我尝试了.val(tplData),但无济于事.

I tried .val(tplData), but to no avail.

是否有其他方法可以通过jQuery设置动态创建的字段的值?

Is there a different way to set the values of fields, via jQuery, that have been created dynamically?

输入字段html如下;

The input field html is as follows;

<div class="field-container">
  <!-- This field is being dynamically created via an ajax call using jQuery -->
  <input type="text" name="priority" id="priority" class="input-group vert-spacer-bottom" placeholder="Priority">
</div>

非常感谢.

编辑 似乎可以动态创建元素,因为如果我在HTML中静态创建输入元素并尝试这些建议,那么它可以完美地工作.但是,如果输入字段是动态创建的,则没有骰子.

EDIT It seems to definitely be something with dynamically create elements, because if I create the input element statically in the HTML and try these suggestions, it works perfect. But if the input fields are created dynamically, no dice.

推荐答案

因此,在将我的头进一步撞向众所周知的代码墙之后,我得以设计出一种解决方案,该解决方案最终表现出色!

So, after further banging of my head against the proverbial code wall, I was able to engineer a solution that ended up working superbly!

动态创建的文本框现在正在接受来自我的jquery代码的值分配.魔术在于根据代码的可见性重新考虑jquery必须如何看待元素.

The dynamically created textbox is now accepting assignment of a value to it from my jquery code. The magic was in rethinking exactly how the element must be seen by jquery in terms of visibility to the code.

首先要考虑的是容器DIV是静态的,并且始终存在于文档中.这意味着在该DIV中创建的任何内容都将严格始终是客户端的.然后,锁定客户端的心境使我想到需要使jQuery意识到新创建的元素.这是通过以下代码实现的:

First thing to account for is that the container DIV is static and always present in the document. This means that anything created in that DIV will strictly be client-side always. Locking into a client-side frame of mind then led me to thinking that jQuery needs to be made aware of the newly created elements. This was achieved by the following code;

var inputElm = '';
inputElm += '<input type="' + data.type + '" name="' + data.name + '" id="' + data.name + '" class="' + data.name + ' input-group vert-spacer-bottom" placeholder="' + data.placeholder + '" />';

$('.field-container').after().html(inputElm);

现在,当我执行代码时...它可以很好地工作并将输入文本框的值设置为所需的值.

Now, when I execute the code...it works beautifully and sets the value of the input textbox to the desired value.

这篇关于jQuery为动态创建的输入文本字段添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆