使用jQuery设置动态创建的文本框的值

时间:2010-01-29 00:03:33

标签: javascript jquery

使用以下代码

var newDiv = $(document.createElement("div"));
var newTextBox;

newTextBox = $(document.createElement("input"))
    .attr("type", "text")
    .attr("id", "textbox")
    .attr("name", "textbox");

newTextBox.val("text");
newDiv.append(newTextBox);
alert(newDiv.html());

我得到以下

<input name="textbox" id="textbox" type="text">

我用

得到同样的东西
$("#textbox").val("test");

使用

newTextBox = $("<input/>");

无济于事

我的价值在哪里?

编辑:SOLTUION

所以,进一步在堆栈中我将我构建的DOM转换为字符串,因为 - 就像munch所提到的那样 - 动态值没有被添加到标记中,它没有显示出来。

感谢您的帮助

5 个答案:

答案 0 :(得分:9)

jQuery不会将值放入创建的元​​素生成的html中。 .attr('value', 'blah').val()都会获取文本输入中输入或更改内容的当前值,并允许您在查看页面上的输入或将其提交给服务器时查看该值。但是,在查看html时你不会看到它。

你仍然可以操纵你想要的所有值,你只是不会看到萤火虫的任何变化,就像改变类别,造型等一样。

AFAIK,不使用jQuery也是如此。同样的事情发生在:

document.getElementById('textbox').value = 'my text'; 

value属性仅用于设置服务器的某些值。使用javascript不需要它。

此外,它取决于您正在使用的输入类型。例如,您将看到value属性更改为隐藏输入,但不会更改文本框。

编辑:

通过将newDiv附加到正文,文本框和值将使用您的代码显示。 Here's a test page。您可以看到代码和预览发生的事情。但是,由于上述原因,警报并未显示任何“价值”属性。

答案 1 :(得分:1)

var newDiv = $(document.createElement("div"));

var newTextBox = $('<input />')
    .attr("type", "text")
    .attr("id", "textbox")
    .attr("name", "textbox")
    .val("my text"); // <-- You can use here...

newTextBox.val("my text"); // <-- or here
newDiv.append(newTextBox);
alert(newDiv.html());

答案 2 :(得分:1)

有一点点黑客你就可以做到。

var newDiv = $('<div/>');
var newTextBox;

newTextBox = $('<input/>')
    .attr("type", "hidden")
    .attr("id", "textbox")
    .attr("name", "textbox");

newTextBox.val("text");
newDiv.append(newTextBox);
newTextBox.each(function(){this.type='text';});
alert(newDiv.html());

首先将其类型定义为隐藏,因为这将允许value属性,然后使用代码将其更改为文本..

答案 3 :(得分:1)

$("#element")[0].setAttribute("value","newvalue");

答案 4 :(得分:0)

也可以这样做

var chip = document.createElement("div"); chip.innerHTML="some value here" card.appendChild(chip)