0

I am defining onclick event to a a href based on a condition

Here's my script:

        <script>
          function comment_pop(id)
         {
             alert(id);
             $('#login_ret_url').val('<?php echo base_url();?>idea/view_idea/'+id+'?action=comment');
             ShowModalPopup('div_login');
         }
        </script>


 <div class="rate_image">
            <a href="<?php if(isset($_SESSION['logged_user']))
                      echo base_url().'idea/view_idea/'.$row['idea_slug'].'?action=comment';
                   else
                       echo 'javascript:void(0)';?>" 
              <?php if(!isset($_SESSION['logged_user']))
                      echo "onclick='comment_pop(".$row['idea_slug'].");'";?>>
            <?php echo $total_comment[$key][0]['total_cont'];?>
            </a>
        </div>

The problem rises in the line

echo "onclick='comment_pop(".$row['idea_slug'].");'";?>>

I am trying to concat the function with the variable so that I can send parameter to the JavaScript function but it's not working.

I think I need to use some escape parameters but I am really new to this.

1
  • What is in $row['idea_slug']? And what does the source show after onclick= ? Commented Apr 29, 2013 at 11:38

3 Answers 3

1

try this

echo "onclick='comment_pop(\'".$row['idea_slug']."\')'";?>>

or making it simple (separeting php and html code)..

 <?php 
        if(isset($_SESSION['logged_user'])){
            $hrefurl=base_url().'idea/view_idea/'.$row['idea_slug'].'?action=comment';
            $onclickurl= "";
        }else{
            $hrefurl = 'javascript:void(0)';
            $onclickurl= 'comment_pop("'.$row['idea_slug'].'");';
  ?>
          <a href="<?php echo $hrefurl;?>" onclick="<?php echo $onclickurl; ?>" >
            <?php echo $total_comment[$key][0]['total_cont'];?>
        </a>
Sign up to request clarification or add additional context in comments.

1 Comment

The PHP code fails (to create valid JavaScript) if the value of $row['idea_slug'] contains a (double) quote.
0

Try escaping the single quote after "onclick=", e.g.

\'

Comments

0

Your current code echoes the idea_slug without quotes, i.e. it won't be a JS string (but a variable identifier, a number or something):

…onclick='comment_pop(some_slug);'…

You want to wrap it in quotes presumably:

echo "onclick='comment_pop(\"".$row['idea_slug']."\");'";

so that you get

…onclick='comment_pop("some_slug");'…

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.