简体   繁体   中英

Get id for each element

I have blog post list and that post have comments. Posts and comments i loop with foreach from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id. When from jquery i try to access to that element post_id is all time the some. I try on submit to debug with alert to see witch post_id will be returned. All time return 270. And when i click to other post comment submit id is not changed.

Posts and comments

<?php foreach($posts as $post): ?>
   <h1><?= $post->title; ?></h1>
    <p><?= $post->text; ?></p>
    <?= if($comments = postComments($post->id): ?>
        <?= foraech($comments as $comment): ?>
             <form id="post_add">
                 <input type="text" placeholder="Say somthing..." name="comment">
                  <input type="hidden" name="pid" class="pid" value="<?= $post->id">
                  <input type="submit">
             </form>
         <?= endforeach; ?>
    <?= endif; ?>
<?= endforeach; ?>



submiteComment: function() {

        var comment_form = $("#comment_add");
        var comment_text = $(".comment_text");
        var pid = $(".pid");  // post id

        $("body").on("submit", comment_form, function(e) {
            e.preventDefault();

            alert(pid.val()); // debug all time return 270 for all comments

            if($.trim(comment_text).length) {

                $.ajax({
                    type: 'post',
                    url: baseurl + '/comment/create',
                    data: {item_id: post_id.val(), comment_text: comment_text.val()},
                    success: function(data) {
                        alert('success');
                    },
                    error: function(t, r, j) {
                        alert(r.responseText);
                    }
                })
            }
        });

Because you are giving each of the post id fields in the form the same name and class, when you access it like this:

var pid = $(".pid");

You will receive all three of the pid elements for your comments into the variable pid. When you do pid.val() it will just return the value of the first one, which is why you will always be seeing the same pid no matter which comment you submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM