将输入值发送到Laravel 5.4中的ajax

时间:2018-02-20 19:22:28

标签: jquery ajax blade

我有一个评论列表现在我想向大家发送回复,我在输入表单中使用了这段代码:

 @foreach($comments as $comment)
        <div class="questions" dir="rtl">
            {{$comment->description}}
            <div class="row">
                <div class="col-sm-2">
                    <input type="hidden" value="{{$comment->id}}" 
                     class="comment_id">
                    <button type="submit" style="float:right" 
                    class="send_answer"> send </button>
                    {{csrf_field()}}
                </div>
                <div class="col-sm-10">
                  <input class="answer" type="text" />
                </div>
            </div>
        </div>
  @endforeach

现在我在ajax中使用此代码但是我在控制台中给出了未定义的错误:

   $(document).on('click', '.send_answer', function (event) {
            var comment_id = $(this).find('.comment_id').val();
            var answer = $(this).find('.answer').val();
            console.log(comment_id);
            console.log(answer);

        });

我如何给出Comment_id并发送给ajax?

2 个答案:

答案 0 :(得分:0)

使用parent()prev()获取jquery中的comment_id

$(document).on('click', '.send_answer', function (event) {
        var comment_id = $(this).parent().find('.comment_id').val();
        var answer = $(this).closest('.questions').find('.answer').val();
        console.log(comment_id);
        console.log(answer);
});

答案 1 :(得分:0)

您可以使用closest()parent()和个人元素idclass

$(document).on('click', '.send_answer', function (event) {
    var comment_id = $(this).closest('.questions').find('.comment_id').val();
    var answer = $(this).closest('.questions').find('.answer').val();
        console.log(comment_id);
        console.log(answer);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questions" dir="rtl">
            <div class="row">
                <div class="col-sm-2">
                    <input type="text" value="121" 
                     class="comment_id">
                    <button type="submit" style="float:right" 
                    class="send_answer"> send </button>
                </div>
                <div class="col-sm-10">
                  <input class="answer" type="text" value='answer' />
                </div>
            </div>
        </div>