Consider the following HTML:
<div id="myfavorites">
<p><button id="saveFav">Save my favorites</button> </p>
<p><a href="http://bit.ly/fzgxya">http://bit.ly/fzgxya</a> <a class="favlinks" href="#">(remove me)</a></p>
</div>
When button is pressed, I want to make a json object with all the links.
$('#saveFav').click(function() {
var toSave = { "searchtext" : $('#searchText').val().trim() };
var links = {};
$('#myfavorites p').each(function(index) {
links[index] = $(this).first('a').attr('href');
});
toSave.links = links;
}
But in $('#myfavorites p').each function, $(this) isn't the p element. I am missing something here. How can I iterate in all p and find the first a element?
And am I construction the object correctly? I mean if I pass it to a php page, will it json_decode correctly?
thanks
try find()
instead of first()
:
links[index] = $(this).find('a').attr('href');
first has no selector parameter
Try this:
$('#myfavorites p').each(function(key,value) {
links[key] = $(value).first('a').attr('href');
});
jquery each docs: http://api.jquery.com/jQuery.each/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With