Yêu cầu thg 4 26, 2018 5:11 CH 144 1 2
  • 144 1 2
+2

Selector in Jquery

Chia sẻ
  • 144 1 2

Mục đich của bài question này là tại e đang làm hệ thống comment sử dụng Ajax.

<form action="{{ URL::route('reply.create', [$comment->id, $curPost->id]) }}" method="POST" class="form-comment">
    <textarea name="reply-comment" id="content-comment" class="form-control"
    <div class="form-group clearfix">
        <button class="btn btn-primary pull-right" id="content-comment-reply" type="submit">Post Reply</button>
    </div>
</form>
<!-- End form 1 -->
<form action="{{ URL::route('reply.create', [$comment->id, $curPost->id]) }}" method="POST" class="form-comment">
    <textarea name="reply-comment" id="content-comment" class="form-control"
    <div class="form-group clearfix">
        <button class="btn btn-primary pull-right" id="content-comment-reply" type="submit">Post Reply</button>
    </div>
</form>
<!-- End form 2 -->
<form action="{{ URL::route('reply.create', [$comment->id, $curPost->id]) }}" method="POST" class="form-comment">
    <textarea name="reply-comment" id="content-comment" class="form-control"
    <div class="form-group clearfix">
        <button class="btn btn-primary pull-right" id="content-comment-reply" type="submit">Post Reply</button>
    </div>
</form>
<!-- End form 3 -->

etc form... etc forms....

Em có 3 ví dụ ạ, còn có thể có rất nhiều form khác nữa... nhưng nội dung tương tự như thế ạ..

Vậy Giờ e selector kiểu sao để khi e nhấn vào button {Post Reply} thì nó sẽ lấy ra được giá trị của textarea đang query ạ...

Thực ra mục tiêu của e không phải là lấy giá trị, mà là dùng nó để gửi request Ajax ạ, và đang bị vướng ở phần này ạ..

Ai có thể cho e biết được kg ạ...

Em cám ơn.

2 CÂU TRẢ LỜI


Đã trả lời thg 4 27, 2018 12:54 SA
Đã được chấp nhận
+5

Quy tắc là bạn phải đi từ gốc của element được click. 😃

$(function() {
    $('button').click(function() {
        var textArea = $(this).parents('form').find('textarea[name=reply-comment]').val();
       console.log(textArea);
    });
});
Chia sẻ
Avatar Jimmy Nguyen @minhtuancnttk39
thg 4 27, 2018 6:46 SA

Em đã làm được theo cách của anh ạ.. Em cám ơn.

Đã trả lời thg 4 27, 2018 1:03 SA
+3

Giải pháp làm nhiều form như thế kia có vẻ không ổn vì phải trả lại nhiều html dư thừa. Tuy nhiên nếu đang làm cách trên thì mình nghĩ bạn có thể sử dụng event onsubmit của form tag thay vì bắt sự kiện click button.

<form method="POST" class="form-comment" onsubmit="alert(1)">
    <textarea></textarea>
    <div class="form-group clearfix">
        <button type="submit">Post Reply</button>
    </div>
</form>
Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí