How to pass parameters in onclick function of generated html

12,524

Solution 1

your old code is producing

<td> <a href="" onclick="remove("1")" class="item-remove"><i class="zmdi zmdi-close"></i></a></td>

which is an incorrect HTML

just replace this

onclick="remove("'.$row_id.'")"

with this

onclick="remove(\''.$row_id.'\')"

see a demo : https://eval.in/830107

Solution 2

onclick="remove("'.$row_id.'")"

Will result in:

onclick="remove("123")"

See where its going wrong? Onclick now contains only the portion remove(, because than a double quote termintes the onclick content.

Share:
12,524

Related videos on Youtube

robins
Author by

robins

Updated on June 04, 2022

Comments

  • robins
    robins almost 2 years

    In my controller code contain html code in appened form.When i pass the parameters to the onclick function, I didn't get the parameters in the corresponding function.

    controller

             foreach ($cart as $item){ 
              $row_id = $item['rowid'];
              //    $count++;
                $output.='
                <tr>
                   <td>'.$item['name'].'</td>
                    <td>'.$item['price'].'</td>
                   <td>'.$item['qty'].'</td>
                   <td>'.number_format($item['subtotal'],2).'</td>
                   <td> <a href="" onclick="remove("'.$row_id.'")" class="item-remove"><i class="zmdi zmdi-close"></i></a></td>
                </tr>
    
                ';
    
         }
    

    script

       function remove(row_id)
        {
    
            alert(row_id);
        }
    

    Onclick function remove(), alert is not working

    • Dharmendra Singh
      Dharmendra Singh almost 7 years
      why you are not using jquery..?
    • Milan Chheda
      Milan Chheda almost 7 years
      Try changing remove("'.$row_id.'") to remove('.$row_id.'), that should work.
    • robins
      robins almost 7 years
      its not working
    • Masum billah
      Masum billah almost 7 years
      if you use remove(2) it works..?
    • Flosculus
      Flosculus almost 7 years
      @DharmendraSingh You've just settled a bet :P