Reputation: 4917
I want to use jQuery to iterate through a list of <div>
s in the following example:
<div id="selectedDefinitionsDiv">
<div id="selectedDef1" class="myclass">
<textarea class="textClass" style="margin-left:5px;width:600px;height:80px;">an adoptive country</textarea>
<input type="button" onclick="removeSelectedDefinition(1)" value="Delete">
</div>
<div id="selectedDef2" class="myclass">
<textarea class="textClass" style="margin-left:5px;width:600px;height:80px;">my adopted state</textarea>
<input type="button" onclick="removeSelectedDefinition(2)" value="Delete">
</div>
</div>
I want to pull out the data in each of the textareas. In the above example that would be an adoptive country
and my adopted state
I have tried
$(#selectedDefinitionsDiv).children('myclass').each(function(i) {
var val = $(this).children('textClass').value;
processString( val );
});
But it doesn't go into the loop at all. Any idea what is wrong with my jQuery?
Upvotes: 1
Views: 1038
Reputation: 148110
Quotes missing in selector
Change
$(#selectedDefinitionsDiv)
to
$("#selectedDefinitionsDiv")
Also change value to val() and add . before class name in selector
$("#selectedDefinitionsDiv").children('.myclass').each(function(i) {
var val = $(this).children('.textClass').val();
processString( val );
});
On more thing closing >
of first div
Upvotes: 3
Reputation: 6003
Try this:
$('textarea').each(function(i) {
var val = $(this).val();
processString( val );
});
Hope this helps.
Upvotes: 0
Reputation: 43823
With your existing code you will probably be getting a JavaScript error since the syntax is illegal. This explains why the code is not executing. The illegal syntax is that
$(#selectedDefinitionsDiv)
is missing the surrounding quotes like so $('#selectedDefinitionsDiv')
.
However, whilst that fixes the syntax error, there are further problems with the selectors.
The CSS class selector in the second and third selectors children('myclass')
and .children('textClass')
is missing the leading .
- it should be .myclass
and .textClass
and you need to use jQuery's .val()
instead of the plain JavaScript .value
since the object you are calling .value
on is a jQuery object.
A simpler solution would be to just supply a more specific selector:
$('#selectedDefinitionsDiv .textClass').each(function(i) {
var val = $(this).val();
processString(val);
});
Upvotes: 1
Reputation: 2251
Upvotes: 2
Reputation: 12037
Just looks to need a bit of tidy up - myclass
needs to be prefixed with a .
and the id
need to be in quotes.
children('.textClass')
also needs a .
prefix:
$("#selectedDefinitionsDiv").children(".myclass").each(function(i)
{
var val = $(this).children('.textClass').val();
processString( val );
});
Upvotes: 1