Reputation: 101
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.
Upvotes: 1
Views: 962
Reputation: 36531
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);
});
Upvotes: 3
Reputation: 42054
If you want to continue to use the inline event handler you need to pass the this keyword.
Change:
onclick="contactnow();"
to:
onclick="contactnow(this, event);"
function contactnow(ele, e)
{
var id=$(ele).siblings('.user_id').val();
alert(id);
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>
<input type="hidden" name="user_id" class="user_id" value="18">
<a class="contactnow" href="#" onclick="contactnow(this, event);">Contact Now</a></td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 2275
I see that you tag jquery, here is an simple example of it.
$('button').on('click', function () {
var answer = $(this).prev().val();
alert(answer)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" value="4">
<button>click me</button>
Upvotes: 0
Reputation: 207900
Remove the inline event handler and use:
$('a.contactnow').click(function() {
console.log($(this).prev('input').val())
})
As I commented above, $(this)
isn't what you think it is since you pass nothing to your function. The you need the .prev()
element, not the .parent()
.
Upvotes: 3