0

I have two questions:

1)- What example is better- when i use onclick in html or when i find the element by in the script?

2)- Is it correct to pass $id value by \<\?=$id\?> in the second example?

<p onclick="message(<?=$id;?>)">Test</p>

<script>
    function message(id){
        alert(id);
    }
</script>

or

<p id="message">Test</p>

<script>
    $("#message").click(function(){
        alert(<?=$id;?>); //<---id
    }
</script>

2 Answers2

1

Your first sample is an outright syntax error. You'd be generating

<p onclick="message-7">Test</p>

Since anything inside the " for the onclick is Javascript code, you're doing "undefined variable minus 7".

If you want to store your 7, you either assign it to a JS variable, or pass it as a function argument:

<script>
 var foo = <?php echo json_encode($id); ?>;
</script>
<!-- or you do -->
<p onclick="somefunction(<?php echo json_encode($id); ?>);">click me</p>

Note the use of json_encode(). It is not necessary in this case, but it's a good habit to get into. You should never be directly dumping a PHP variable into a javascript context with out it. Remember that the client browser will never see your PHP code. It'll just see whatever javascript you're generating, and if the PHP value contains illegal javascript, you'll just be producing a javascript syntax error and killing the entire block.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0
Community
  • 1
  • 1
Thomas Landauer
  • 7,857
  • 10
  • 47
  • 99