Javed
Javed

Reputation: 6239

how to select a class or id when a button is clicked with jquery

My div with class="vote" is

<div class="vote">
<input type="hidden" name="q_id" class="q_id" id="q_id" q_id="{{ result.object.id }}" value="{{ result.object.id }}">
<button type="submit" class="downvote" value="downvote">downvote</button>

and there are several divs of this type on my html page,

My ajax call with jquery is

$('.downvote').click(function() {
var q_id=$(this).attr('q_id')
console.log(q_id)
$.ajax( {
    type: 'GET',
    url:"http://127.0.0.1:8000/q/downvote/",
    data:q_id,
    success: searchSuccessDown,
    dataType: 'html'
});
});
function searchSuccessDown(data) {
console.log('downvoted successfully');}

I am newbee and my question is when a downvote button is clicked(there are several downvote buttons on the page) how to select input tag with id="q_id" or class="q_id" for the corresponding div with class="vote" and pass its value through ajax data.

Upvotes: 3

Views: 1331

Answers (3)

Umair Shah
Umair Shah

Reputation: 2280

Here is exactly how you should be doing it :

HTML :

<div class="vote">
<form method="post" action="" id="downvote_form">
<input type="hidden" name="q_id" class="q_id" id="q_id" q_id="{{ result.object.id }}" value="{{ result.object.id }}">
<button type="submit" class="downvote" value="downvote">downvote</button>
</form>

JavaScript :

<script>
$(document).ready(function() {
        $('#downvote_form').on('submit', function(e) {
                $.ajax({
                        url: 'http://127.0.0.1:8000/q/downvote/',
                        data: $(this).serialize(),
                        type: 'POST',
                        success: function(data) {
                            if (data == "success") {
                                console.log(data);
                                window.location.href = "success.php"; //=== Show Success Message==
                            }
                        },
                        error: function(data) {
                            alert("You have an error); //===Show Error Message====
                            }
                        }); e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
                });
        });
</script>

Upvotes: 1

James Waddington
James Waddington

Reputation: 2905

One way is to get the parent element (which is the vote div), then find the q_id element inside that:

var q_id = $(this).parent().find('.q_id').val();

Here's a quick fiddle: https://jsfiddle.net/1m56g6jL/

Upvotes: 4

user4615488
user4615488

Reputation:

do like this:

...click(function (e) {

var qIdNode = $(e.target)
.closest(".vote") // navigates to the closest parent that have the class vote
.find('.q_id'); // then finds the sibling q_id element of the target/clicked element...

});

Upvotes: 0

Related Questions