簡體   English   中英

使用jQuery保留文本框值

[英]Persisting textbox value using jQuery

我想保存新輸入的值,以便重新使用它們。 但是,當我嘗試執行以下操作時,它不起作用:

// 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>

如果要使用舊/初始文本框值,則可以按以下方式使用單行代碼。

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

如果要在文本框中輸入當前值,則可以使用以下代碼$(“#form_id”)。find(“ input [type ='text'] id * ='current_amount']”)。val();

您要保存以前的值並在下一個change事件中使用嗎?

本示例使用.data保存以前的值。 參見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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM