Talha Aslam Talha Aslam - 3 months ago 9
Javascript Question

Table Anchor Click Get Parent Class Value

Here is my html code:

<td>
<input type="hidden" name="user_id" class="user_id" value="18">
<a class="contactnow" href="#" onclick="contactnow();">Contact Now</a>
</td>


my javascript function is as follow's:

function contactnow()
{
var id=$(this).parent('.user_id').val();
alert(id);
}


I need to get the value of hidden field on click on this anchor, these anchor's are multiple on same page as looping data from database.

Answer

Pass reference in onclick attribute.

<a class="contactnow" href="#" onclick="contactnow(this);">Contact Now</a>

use this

function contactnow(e)
{
   var id=$(e).parent().find('.user_id').val();
   //or
   var id=$(e).siblings('.user_id').val();
   alert(id);
}

However instead of using javascript in html attributes you can separate your javascript entirely which is lot more cleaner and you don't have to repeat onclick everytime for it to work in multiple elements. Remove onclick attribute

Html

<a class="contactnow" href="#">Contact Now</a>

JS

$('.contactnow').click(function(){
    var id=$(this).parent().find('.user_id').val();
    //or
    var id=$(this).siblings('.user_id').val();
    alert(id);
});

// if you are using dynamically added element use

 $(document).on('click','.contactnow', function(){
    var id=$(this).parent().find('.user_id').val();
    //or
    var id=$(this).siblings('.user_id').val();
    alert(id);
});
Comments