zazvorniki
zazvorniki

Reputation: 3602

Jquery only grabbing the first id for a list of items

I'm working on turning divs into links using jquery. To make the links work I need to get back both the story_id and chapter_id of each chapter, but when I do I only get back the first chapter_id...so all the links are the same. Am I making scene?

My jquery looks like this for a story block.

$('.storyInnerBlock').click(function(){
  var story_id = $('.story_id').val();
  var chapter_id = $('.chapter_id').val();
  $ (location). attr ('href', 'http://www.writeyourfiction.com/index.php/story/readStory/'+story_id+'/'+chapter_id);
});

I set up a fiddle to kind of show whats going on.

http://jsfiddle.net/zazvorniki/vwnCb/6/

Any help would be much appreciated! :)

Upvotes: 0

Views: 77

Answers (2)

7stud
7stud

Reputation: 48649

val() only returns the value of the first element in the matched set, so story_id and chapter_ id are the same for all your links. You need to step through each match in a loop. Actually, you just need to use $(this) inside your click() function to refer to the current element in the matched set because the click() function does an implicit loop over the matched set:

$(document).ready( function() {

  $('.storyInnerBlock').on('click', function(){
    var story_id = $(this).children('.story_id').val()
    var chapter_id = $(this).children('.chapter_id').val()
    console.log(story_id + "<--->" + chapter_id);
  });

});

Upvotes: 0

David Thomas
David Thomas

Reputation: 253446

I'd suggest:

$('.storyInnerBlock').click(function () {
    var context = $(this).closest('.storyInnerBlock'),
        story_id = context.find('.story_id').val(),
        chapter_id = context.find('.chapter_id').val();

    alert('story ' + story_id);
    alert('chapter ' + chapter_id);
});

JS Fiddle demo.

Effectively this is because the getter methods (those methods that return the value, text or HTML (among others)) return the content of only the first element of the matched set returned by the selector.

The above approach supplies a context, finding the closest ancestor .storyInnerBlock element and restricting the search, with find(), within that element.

References:

Upvotes: 1

Related Questions