I have some element with some data. I need to create changing field for it. So i use textarea to change text in this element. Everything working nice but when i want to add condtion with text langht something is not working right… This is my code and some fiddle (http://jsfiddle.net/qzzKA/) for it. Thx for help…
<div class="textchange_box">
<span class="desc">data<br>data
</span>
<textarea name="desc" class="textfield"></textarea>
<span class="change">change</span>
<span class="save">save</span>
</div>
and jquery:
$(".change").live('click', function () {
$(this).prev('.textfield').css('display','block');
$(this).prevAll('.desc').css('display','none');
$(this).next('.save').css('display','block');
$(this).css('display','none');
});
$(".save").live('click', function () {
var default_value = $(this).prev('.desc').text().replace(/\r\n|\r|\n/g,"<br/>");
var actual_value = $(this).prev('.textfield').text().replace(/\r\n|\r|\n/g,"<br />");
$(this).prevAll('.textfield').css('display','none');
$(this).prev('.change').css('display','block');
$(this).css('display','none');
if (actual_value.length < 0) {
$(this).prev('.desc').replaceWith('<span class="desc">' + default_value +'</span>');
}
else if (actual_value.length > 0) {
$(this).prev('.desc').replaceWith('<span class="desc">' + actual_value +'</span>');
}
});
Replace your following line:
for this one:
because when a string is empty its length is zero not a negative number.
UPDATE:
You have other errors, your following two lines:
should be like this:
So using
prevAll()instead ofprev()and usingval()for textarea instead oftext().Also you need to use
prevAll()here:so it would be:
See working fiddle .
Basically the most common error is you thought
.prev()will traverse all previous siblings, while for that you have to useprevAll()