开发者

Question about selecting form children jquery

开发者 https://www.devze.com 2022-12-21 05:02 出处:网络
Again I\'m asking question about comment form, I\'m making an image website and every image has its own comment form, so when I submit form I do like this :

Again I'm asking question about comment form, I'm making an image website and every image has its own comment form, so when I submit form I do like this :

$('#comment_form').live('submit', function() {
 ...

So in order to select only this form textearea value I tried using this but I get undefined error here is how I tried :

$('#comment_form').live('submit', function() {
 image_comment_text=$(this).closest("#comment_text").val(); //textarea id is comment_text

I tried to used find(), its working but when I submit comments for few images I get comments 2 or 3 times as I should, because find finds all occurrences of textarea with comment_text id .. how can I do this ?

@molf , here is HTML generated by javascript:

var xHTML = "<div class=\"addComment\">";
   xHTML += "<form action=\"<?=base_url()?>images/post_comment/" + post + "\" method=\"post\" class=\"comment_form\" name=\"comment_form\">";
   xHTML += "<input type=\"hidden\" class=\"comment_post_id\" name=\"comment_post_id\" value=\"" +post + "\"/>"; 
   xHTML += "<textarea class=\"comment\" name=\"comment_text\" rows=\"8\" cols=\"40\"></textarea>";
      xHTML += "<input type=\"submit\" name=\"submit\" class=\"post_image_comment\" value=\"Comment\"><span> Don't make it too big!</span>";
   xHTML += "</form></div>";

EDIT

When I print to console log the value of textarea I get only one result as I should, now when I try to append the ul comments I get 2 of the same va开发者_JAVA百科lues .. here how it goes ..

<ul class="comments"></ul> 

below is the comment form which is not in the document at all, when certain anchor is clicked the form pops out below .comments , when form submits I want to append the comments to add the new comment to list items of existing unordered list comments , here is the whole code :

$('form[name^="comment_form"]').live('submit', function(event) {
  r= $(this).find('> .comment').val();

                $('<div class="overlay"></div>')
    .appendTo('.addComment')
             .fadeIn(200, function() {
          $('.comments')
             .append('<li id="new_append">' + r + '</li>')
              .children(':last')
           .height($('.comments li:last').height())
           .hide()
           .slideDown(800, function() { 
             var bodyHeight = $('html').height();
            $('.addComment').fadeOut(500, function() {
              $('html').height(bodyHeight);
           $('h2#leaveAComment').fadeOut(200, function(){$(this).text('Thank you for your comment!').fadeIn(200)});
          });
         });  
        $('html, body').scrollTo( $('#new_append'), 800 );
        });
    event.preventDefault();
            }); 

EDIT II @patrick

The javascript which loads the comment form is above .. here is HTML :

-------------BEGIN FOR EACH--------------

<div id="image-12" class="image_content">
<img src="..." />
 <ul class="comments hidden"> //This is where the comments are appended to <li></li>

 </ul>

<div style="float: left; display: block; width: 100%;">
<a id="image_comment-12" class="image_comment" onclick="showComments('12');" href="javascript:;">Add Comment</a>
</div>

  <div id="addComment-12">//this is where the comment form loads

  </div>

</div>

----------END--- FOR EACH--------- image ...


First of all, change your selector for your form. I think you can select form by name using the id selector, but you're not supposed to duplicate ids on a page, so jQuery live is probably only watching the first form. This is just a guess, though.

Also, it doesn't matter what class/id you use for your textarea. If you're only going to have one textarea per form, you can use the :text selector. When finding children, I like to use the children selector.

$('form[name="comment_form"]').live('submit', function() {
  image_comment_text = $(this).find('> :text').val();
});

If you're using name instead of id because you're going to have multiple forms, I would suggest changing the name to comment_form_'image_id', then your selector would be: $('form[name^="comment_form"]')
Notice the ^ which requires the name to start with 'comment_form'. That way, you can have unique form names (comment_form_234, comment_form_235) and still have the desired effect.

Edit:

I looked at your code update, and it looks to me like you're ignoring the context of the current form in your function. For instance, when you use the selector $('.comments').append(... you're appending to all elements on your page which match that selector. In order to retrieve the proper elements, you'll have to always use your selector as $(this).find(' > .comments').append(... which will work within the context of the submitted form.

I took a few minutes to edit your code, I haven't run it or anything, but it should be close to what you're trying to do. I hope it at least gets you started in the right direction:

$('form[name^="comment_form"]').live('submit', function (event) {
    r = $(this).find('> .comment').val();
    /* get addComment-classed element */
    var addComment = $(this).find(' > .addComment:first');

    /* get comments-classed element */
    var comments = $(this).find(' > .comments:first');

    $('<div class="overlay"></div>').appendTo(addComment).fadeIn(200, function () {
        /* note comments element, not selector */
        $(comments).append('<li id="new_append">' + r + '</li>').children(':last').height(
        /* again, element */
        $(comments).find(' > li:last').height()).hide().slideDown(800, function () {
            var bodyHeight = $('html').height();

            /* again, element */
            $(addComment).fadeOut(500, function () {
                $('html').height(bodyHeight);
                $('h2#leaveAComment').fadeOut(200, function () {
                    $(this).text('Thank you for your comment!').fadeIn(200)
                });
            });
        });
        $('html, body').scrollTo($('#new_append'), 800);
    });
    event.preventDefault();
});

I added comments in the code, but notice that the addComments and comments selectors are 'cached'. If you're going to be accessing these elements multiple times, storing them in a variable before using them will cut back on DOM traversals. This should really solve your comments being added to multiple elements on your page.


How many comment_forms do you have on a each page? For correct HTML you should only have one id='comment_text' and one id='comment_form' per page.

Consider changing your ids to class='comment_text' and finding with .comment_text rather than #comment_text


I think from your latest comments the issue may be the way you are dynamically adding your form/comments textbox to the page.

Once you've entered comments and submitted them do you then remove the form you've dynamically added? I would recommend this as if not I think your DOM structure is getting confused causing the problems you are experiencing.


First, the find() method was the correct way to go if used within the proper context.

Second, it sounds like you are re-using IDs. This is not allowed. An ID can be used only once on a page.

The closest() function searches 'up' from (and including) the DOM element. The find() function searches the content of the element.

EDIT:

I assume the form is being submitted when the user clicks the submit button. I also assume that there's more to your submit() handler than is shown. Is that correct?

Sometimes you need to add $(this).preventDefault(); in order to keep the form from being submitted in your code, as well as by the default behavior of the 'submit' button.

The following does the same thing (essentially) as find(). It will find the item with the .comment_text class within the form being submitted. So it should only grab the value of one item:

image_comment_text=$(".comment_text", this).val();


You are getting duplicate comments because you aren't removing the previous add comment form. Try adding this to the end of your .slideDown callback function:

$(this).remove();

Here is the full submit function, I made a few changes/additions:

  • I removed the > from the find('.comment') as it isn't necessary
  • Changed the new append to a class, then removed it after you scroll to it.
  • Removed the form when complete
  • Changed the event.preventDefault(); to return false;... this is more of a personal preference than anything.

I hope this helps :)

 $('form[name^="comment_form"]').live('submit', function(event) {
  r = $(this).find('.comment').val();
  $('<div class="overlay"></div>')
   .appendTo('.addComment')
   .fadeIn(200, function() {
    $('.comments')
     .append('<li class="new_append">' + r + '</li>')
     .children(':last')
     .height($('.comments li:last').height())
     .hide()
     .slideDown(800, function() {
      var bodyHeight = $('html').height();
      $('.addComment').fadeOut(500, function() {
       $('html').height(bodyHeight);
       $('h2#leaveAComment').fadeOut(200, function(){$(this).text('Thank you for your comment!').fadeIn(200)});
       $(this).remove();
      });
     });
     $('html, body').scrollTo( $('.new_append:last'), 800 );
     $('.new_append').removeClass('new_append');
   });
  return false;
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号