Umerm Umerm - 3 months ago 11
Javascript Question

Find value of sibling children

I am trying to find the value of span. When I click on anchor it should give me value inside span. It should be dynamic.Here is the html

<div class="member-info">
<h2>Total Votes : <span>1</span></h2>
<a href="3" class="btn-system btn-medium border-btn vote_btn" data-target="#danger" data-toggle="modal">Vote</a>
</div>


Here is the jquery code

$('.vote_btn').on('click',function(){
var id = $(this).attr('href');
var method_url = "<?php echo base_url(); ?>Home/vote/"+ id;

$.ajax
({
type: "POST",
url : method_url,
success:function(data)
{

if(data=='1')
{
var votes = $(this).siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Thanks you and come back tomorrow to vote again.');
}else if(data=='0')
{
var votes = $(this).siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Sorry you have already voted today, please come back tomorrow to vote again.');
}

$('#response_modal').modal('show')
}
});
});


This code is giving me undefined value whereas I want to get the value available in span element when I click on anchor vote. Please help

Answer

you cannot access $(this) in success function directly ,assign a variable and access it in success function

 $('.vote_btn').on('click',function(){
    var id = $(this).attr('href');
    var method_url = "<?php echo base_url(); ?>Home/vote/"+ id;
    var $current_element = $(this);

    $.ajax
    ({
        type: "POST",
        url : method_url,
        success:function(data)
        {

            if(data=='1')
            {
                 var votes = $current_element.siblings('h2').children('span').text() ; alert(votes);
                $("#vote_response").html('Thanks you and come back tomorrow to vote again.');
            }else if(data=='0')
            {
                var votes = $current_element.siblings('h2').children('span').text() ; alert(votes);
                $("#vote_response").html('Sorry you have already voted today, please come back tomorrow to vote again.');
            }

            $('#response_modal').modal('show')
        }       
    }); 
});
Comments