Here is my fiddle: http://jsfiddle.net/dQ6vZ/22/
I have a case where I have repeating elements with some numeric values.
<div class="chars">
<textarea></textarea>
<span class="myVal">5</span>
<span class="pres"> - preserved: 5</span>
</div>
<div class="chars">
<textarea></textarea>
<span class="myVal">10</span>
<span class="pres"> - preserved: 10</span>
</div>
On keyup event (when typing text) I am supposed to preserve the very first original value from span element with class myVal but update the value in the same element as I type.
So if the original value was 5, I need to keep 5 while I replace the value visible to the user with a new value.
My beginning looks something like this:
var new_value = 0;
$( ".chars" ).keyup(function() {
var preserved_increment = parseInt($(this).find(".myVal").text());
var text_length = parseInt($(this).find("textarea").val().length);
new_value = text_length + preserved_increment;
$(this).find(".myVal").text( new_value );
$(this).find(".pres").text( " - not preserved: " + preserved_increment );
});
Use the data function provided by jQuery for this task.
I have updated your code to preserve the original value inside the text area. jsfiddle
To access the original value, simply call:
var originalValue = $(this).find(".myVal").data("original")
use data-* attributes, and then use jQuery's .data
method to get the value
HTML
<div class="chars">
<textarea></textarea>
<span class="myVal" data-preserved="5">5</span>
<span class="pres"> - preserved: 5</span>
</div>
JS
var preserved_increment = parseInt($(this).find(".myVal").data("preserved"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.