如何使用jquery更改变量中输入框的值?

时间:2014-02-04 09:03:05

标签: javascript jquery html forms

我有一个包含带输入框的表单的变量,我想使用jquery更改所述输入框的value属性。到目前为止,我可以更改值,但它不会在外部html中更改。这是我到目前为止所得到的:

$("a").click(function(event) {
    var form_content = "<form><input id=\"name\" value=\"Test value\"/></form>";
    var test = $('<div />').html(form_content).find('#name').val('New test value').parent();
    alert(test.find('#name').val());
    alert(test.html());
    return false;
});

也可在jsfiddle处找到。第一个alert显示"New test value",但第二个alert没有显示任何关于如何存储此新值的提示 - 基本上它返回的值与原始变量{{1}相同}。

我看了here,但无法理解我做错了什么。

有人可以帮我点点滴滴,可能会给我一些如何更改form_content中存储的html的提示吗? (似乎有很多关于如何在普通静态HTML中执行此操作的示例,但遗憾的是,这不是我的选择。)谢谢!

3 个答案:

答案 0 :(得分:1)

$("a").click(function(event) {
    var form_content = "<form><input id=\"name\" value=\"Test value\"/></form>";
    var test = $('<div />').html(form_content).find('#name').attr('value', 'New test value').parent();
    alert(test.find('#name').attr('value'));
    alert(test.html());
    return false;
});

更新您的查询,其工作正常......

答案 1 :(得分:0)

不要使用.val('新测试值'),而是使用.attr('value','new test value')

答案 2 :(得分:0)

只需输入您输入元素的类型即可 尝试

      <input type="hidden" id="name" value="Test value">