Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass parameter to javascript function

I have the following javascript.

<script>
function getMethod(id){alert(id);}

</script>

following is html,

<table id="tbl1">
<tr>
<td><input type="button" onclick="getMethod()"/></td>
</tr>
</table>

I need to pass table id "tbl1" to javascript method getMethod on click event of html button. so what should I do? what I want is something like this,(Passing table ID onclick method's parameters)

<input type="button" onclick="getMethod('$("tbl1").ID')"/>

how can I do this?

Thanks


1 Answers

Don't pass anything rather than the this reference and do,

HTML

<input type="button" onclick="getMethod(this)"/>

JS

function getMethod(elem){
   alert($(elem).closest('table').attr('id'));
}

In the above function we have used .closest() to grab the parent table. and we have used .attr('id') to retrieve its id.

DEMO

like image 87
Rajaprabhu Aravindasamy Avatar answered Dec 02 '25 15:12

Rajaprabhu Aravindasamy



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!