DelightedD0D DelightedD0D - 3 months ago 18
HTML Question

Manipulating textarea value for in memory jQuery object

Given an array of strings where each string is the html for a form element that has a value assigned, I'd like to loop over the array and remove the values for each element.

I need to end up with the same array of strings but where:


  • input
    and
    textarea
    element values are all set to ''

  • select
    element options are all deselected

  • checkbox
    elements are all unchecked

  • I set the element backgrounds to yellow just to show the text areas are being selected



To do this, I figured I'd wrap the elements in a div, set all the element attributes, then get the div's html.

This works for all the elements except textareas

I've tried


  • .val('')

  • .attr('value', '')

  • .prop('value', '')



None worked to remove the value of a textarea in memory.



var elements = [
'<input type="checkbox" checked>',
'<input type="text" value="1041">',
'<input type="text" value="activities">',
'<textarea>some text</textarea>',
'<select><option value=""></option><option value="1" selected>1</option></select>',
'<select><option value=""></option><option value="1" selected>1</option></select>',
'<textarea>some text</textarea>'
];

var newElements = [];
$.each(elements, function(i, item) {
var $temp = $('<div>').html(item);
var $tempElements = $temp.find('input:not(.row-select), textarea, select').addClass('test');
//$tempElements.val(''); // doesnt work at all
$tempElements.attr('value',''); // works for text inputs but not textarea
$tempElements.attr('checked', false);
$tempElements.find('option').attr('selected', false);
newElements.push($temp.html());
});

$('#result').html(newElements.join(''));

.test{
background-color:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>





Expected result:



var elements = [
'<input type="checkbox">',
'<input type="text" value="1041">',
'<input type="text" value="activities">',
'<textarea>some text</textarea>',
'<select><option value=""></option><option value="1" selected>1</option></select>',
'<select><option value="" selected></option><option value="1">1</option></select>',
'<textarea></textarea>'
];


Here is a jsFiddle



I do understand that I could just append the html to a div in the dom and do what I need there, but Im curious if there isn't a way to do this in memory.

Answer

Just use .text('') to remove the content of textarea.

$tempElements.text('');

And you don't need prop when using attr before.

// change
$tempElements.attr('value', '').prop('value', '');
// to
$tempElements.attr('value', '');

Wokring example.