Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 779
javed Avatar asked Dec 04 '25 13:12

javed


2 Answers

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/

like image 147
James Waddington Avatar answered Dec 07 '25 04:12

James Waddington


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>
like image 23
Umair Shah Yousafzai Avatar answered Dec 07 '25 02:12

Umair Shah Yousafzai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!