views:

22

answers:

3

I have several dynamically created links and forms on one page named with IDs sub_comment_form_[id] and sub_add_comment_[id], respectively. I'm trying to:

  1. Hide all forms when the page loads
  2. Bind a click event to the link directly above the form to hide/show the form.

I'm not sure if there is a problem with my selectors, or if jQuery simply does not allow binding on multiple objects at once. Here is my code:

HTML

<a href="#" id="sub_add_comment_to_answer_[id]">Add comment</a>
<form id="sub_comment_form_to_answer_[id]"...

jQuery

$("form[ @id^='sub_comment_form' ]").hide();

$("a[ @id^='sub_add_comment' ]").click(function() {
  var sibform = $(this).next("form");

  if (sibform.is(':hidden')) {
    $(this).text('Cancel');
    sibform.slideDown('fast');
  } else {
    $(this).text('Add comment');
    sibform.slideUp('fast');
  }
});
+4  A: 

If you're using a newer version of jQuery (1.3+) there's no @ on attribute selectors anymore, it just looks like this:

$("form[id^='sub_comment_form']").hide();
//and..
$("a[id^='sub_add_comment']").click(function() {

This first one was also missing a closing brace, so be sure to fix that too :)

Also, be sure both of these are wrapped in a document.ready handler so they execute after the DOM is ready, like this:

$(function() {
  $("form[id^='sub_comment_form']").hide();
  $("a[id^='sub_add_comment']").click(function() { ... });
});

Alternatively, instead of these ID starts-with selectors you could use a class, for instance:

<a href="#" class="addComment">Add comment</a>

And bind it like this:

  $("a.addComment").click(function() { ... });
Nick Craver
+2  A: 

Line 1 is missing the closing ']' so it should be...

$("form[@id^='sub_comment_form']").hide();
BigRossLabs
+1 for sharp eyes. Thanks!
Wraith
+1  A: 

It is also a good practice to prefix variables containing jQuery objects with a $.

var $sibform = $(this).next("form");

This way you always know when you're dealing with a jQuery object and not. And thereby keeps you from binding a jQuery object in itself.

Dag Einar Monsen