2

I want to pass parameters to onclick jquery function from html onclick event.

html statement rendering in PHP

$name = "abcd";
for ($i=0;$<10;$i++){
$text .= '<tr>
             <td>'.$i.'</td>
             <td><div id="name">'.$name.'/div>
                 <a class="href" onclick="callJSFunc($i,\''.$name.'\')" ></a>
             </td>
          </tr>';
}

javascript..

function callJSFunc(i , name){
alert(i+"  "+name);
}

I want to convert it into someting...

$(".href").click(function(i,name,event){
alert(i+"  "+name);
});
1
  • 1
    The callJSFunc($i will not insert the value of $i since you're using a single quoted string.. Commented Jan 11, 2013 at 13:06

3 Answers 3

6

Why don't you try in some other way

$name = "abcd";
for ($i=0;$<10;$i++){
$text .= '<tr>
         <td>'.$i.'</td>
         <td><div id="name">'.$name.'/div>
             <a class="href" data-id="'.$i.'" data-name="'.$name.'" ></a>
         </td>
      </tr>';
}

And in jQuery onClick

$(".href").click(function(){
    alert($(this).attr('data-id')+"  "+$(this).attr('data-name'));
});
Sign up to request clarification or add additional context in comments.

Comments

3

You cannot change the way events are fired but you can always store those parameters as data-* attributes in markup and extract them inside the event handler. What you request is to subscribe for the event and the event object to naturally mutate according to what you desire as parameters, however the browser has no way to figure out what you require.

What I mean by using data-* attributes is to store the data inside your DOM element:

<a class="href" data-index="$i" data-name="$name" href="someHref" />

jQuery:

$('.href').click(function (event) {
    var index = $(this).attr('data-index'); // Yields a string use data() for other data types
    var name = $(this).attr('data-name'); // Yields a string use data() for other data types
});

1 Comment

You can also get the data using $(this).data("index/name").
0

It is better to do this with jQuery instead of sending the parameters with PHP.

You can do something like this in your javascript:

$('a.href').click(function( event ) {
  var index = $('table').index(this); // Containing table
  var name = $(this).siblings('#name').innerHTML;
  alert( index + ' ' + name );
});

Btw, an id should be unique. Your code generates 10 table rows with in every one of them the id '#name'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.