使用jQuery保留文本框值

时间:2010-10-12 22:12:53

标签: javascript jquery jtemplates

我想保存新输入的值,因此我可以重复使用它们。但是,当我尝试执行以下操作时,它不起作用:

// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val()); 

当行执行时,不会生成错误,但Firebug不会显示 el 的value属性已更改。我也试过以下,但没有运气:

$(el).val($(el).val()); 

我尝试这样做的原因是当我使用jTemplates将新内容附加到容器时保留文本框中的值。旧内容保存在变量中,然后预先添加到容器中。但是,输入文本框的所有值都会丢失

var des_cntr = $("#pnlDesignations");
    old = des_cntr.html();
    des_cntr.setTemplate( $("#tplDesignations").html() );
    des_cntr.processTemplate({ 
                                Code: code, 
                                Value: val,
                                DivisionCode: div,
                                Amount: 0.00
                            });
    des_cntr.prepend(old);

这是模板:

<div id="pnlDesignations">
    <script type="text/html" id="tplDesignations">
        <div>
           <label>{$T.Value} $</label>
           <input type="text" value="{$T.Amount}" />
           <button>Remove</button>
           <input type="hidden" name="code" value="{$T.Code}" />
           <input type="hidden" name="div"  value="{$T.DivisionCode}" />
        </div>
    </script>
</div>

2 个答案:

答案 0 :(得分:1)

您想保存以前的值并在下一个change事件中使用吗?

此示例使用.data保存以前的值。 See on jsFiddle

$("input").change(function(){
    var $this = $(this);

    var prev = $this.data("prev"); // first time is undefined

    alert("Prev: " + prev + "\nNow: " + $this.val());

    $this.data("prev", $this.val()); // save current value
});

jQuery .data

答案 1 :(得分:1)

如果您想要旧/初始文本框值,可以使用单行代码,如下所示。

var current_amount_initial_value = $(“#form_id”)。find(“input [type ='text'] id * ='current_amount']”)。prop(“defaultValue”);

如果要在文本框中显示当前值,可以使用以下代码 $( “#form_id”)找到( “输入[类型= '文本'] ID * = 'current_amount']”)VAL();