Shane Wade
Shane Wade

Reputation: 99

How to correct data inside a loop in jquery

I have below code. when I click reply link, it will show a comment box. I want 2 points. or give me best way to do my work.

  1. When 1 comment box open other must be hide.
  2. when I click on send button correct value should send vie serialize values.

These are the codes PHP code

<?PHP 
    for($i = 1; $i < 10; $i++)
    {
    ?>  
    <div>comments text etc etc...</div>
    <a href="" class="reply-comment"> Reply </a>
    <div class="reply-comment-form" style="display:none;">
        <form class="comment_form" method="post">     
            <textarea name="comment_box" rows="6" class="span10"></textarea> <br /><br />
            <input type="button" onClick="send_comment()" class="btn btn-primary" value="send" />
        </form> 
    </div>
<?PHP 
   } 
?>

Jquery code

<script> 
    $(function(){
        $('.reply-comment').on('click', function(e){ 
            e.preventDefault();
            $(this).next('.reply-comment-form').show();
        });
    });


    function send_comment()
    {   
        $.ajax({   
           type: "POST",
           data : $('.comment_form').serialize(),
           cache: false,  
           url: 'test.php',  
           success: function(data){

           }   
        });   
    }
</script>

test.php file no need. I am checking values through firebug. please help me to clarify this problem. or give me best way to do my work.

I am stuck since 2 days. Thank you for your valuable time.

Upvotes: 1

Views: 51

Answers (2)

Shane Wade
Shane Wade

Reputation: 99

I found a solution. @void helped me for this.

    $(".test").on("click", function(){

    var _data = $(this).parent().serialize();
    $.ajax({   
        type: "POST",
        data : _data,
        cache: false,  
        url: 'test.php',  
        success: function(data){

        }   
    }); 

});

Thanks!

Upvotes: 1

void
void

Reputation: 36703

For the first one

$('.reply-comment').on('click', function(e){

    e.preventDefault();

    // Hide others
    $(".reply-comment-form").hide();

    // Show the one which is required
    $(this).next('.reply-comment-form').show();

 });

And for second, do a .on("submit"... on the form and it will serialize the right input fields only.

UPDATE:

<form class="comment_form" method="post">     
      <textarea name="comment_box" rows="6" class="span10"></textarea> <br /><br />
      // Change type to submit and remove onclick
      <input type="submit" class="btn btn-primary" value="send" />
</form> 

jQuery:

$(".comment_form").on("submit", function(e){
    e.preventDefault(); // Here
    var _data = $(this).serialize();
    $.ajax({   
        type: "POST",
        data : _data,
        cache: false,  
        url: 'test.php',  
        success: function(data){
            console.log(data);
        }   
    });   

});

Upvotes: 1

Related Questions