Itai Sagi
Itai Sagi

Reputation: 5615

jquery proper chaining?

I have the following:

$("#modal-controls").html(html)
  .find("#pic_caption").val(data.pic_caption)
  .find("#pic_desc").val(data.pic_desc);

Basically, I change the html of something, search for inputs and change their values. it changes the 1st one, but doesn't proceed to change the 2nd input, How will I go about writing it properly using chaining? or must I seperate it to 2 different jQuery objects?

Thanks.

Upvotes: 0

Views: 361

Answers (4)

mVChr
mVChr

Reputation: 50215

Assuming your HTML structure is like this:

<div id="modal-controls">
    <input type="button" id="pic_caption" value="">
    <input type="button" id="pic_desc" value="">
</div>

You need to use jQuery end() (DOCS) to return the filter to the original selector for the chained find():

$("#modal-controls").html(html)
  .find("#pic_caption").val(data.pic_caption)
  .end()
  .find("#pic_desc").val(data.pic_desc);

Upvotes: 1

Schreinbo
Schreinbo

Reputation: 235

Your selector is not looping through the matches, it is only hitting the first one. Try this one assuming you have multiple modal-controls...

$("#modal-controls").each(function(index){
  $(this).html(html)
  .find("#pic_caption").val(data.pic_caption)
  .find("#pic_desc").val(data.pic_desc);
});

Upvotes: -1

Phil
Phil

Reputation: 165070

Your problem is because the first find() places the current chain at #pic_caption. Use end() to return to the previous selector chain, eg

$("#modal-controls").html(html)
  .find("#pic_caption").val(data.pic_caption).end()
  .find("#pic_desc").val(data.pic_desc);

Upvotes: 2

Avaq
Avaq

Reputation: 3031

Have a look at jQuery.fn.end(). You can add it to the chain to revert back to the previous set of matched elements.

$("#modal-controls").html(html)
  .find("#pic_caption").val(data.pic_caption).end() //<--
  .find("#pic_desc").val(data.pic_desc);

Upvotes: 1

Related Questions