0

What I have:

Try to pass variable to javascript method in such way:

$name = (string) $form->attributes()->name;
$show = 'show("'.$name.'")';
echo '<input type="radio" onclick="'.$show.'">'.$form['description'].'<br />';
print_r($show); // show("feedback")
...
<script>
function show(name) {
    //DEBUG HERE!
    ...
}
</script>

What a problem:

In browser's debugger I can see that into show method I've passed the whole form (means that argument name equals to the whole form).

Question:

Why does it happen? How to pass to js-method only form's name?

volodymyr3131
  • 335
  • 2
  • 5
  • 16

2 Answers2

2

I think you are just missing some quotes around it:

echo '... onclick="show(\"'.$name.'\")> ...';

Note the \" I put around $name. In your code, if $name = "Foo", it would write show(Foo) instead of show("Foo").

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
0

I think you are not escaping the string properly to be used by the JS function. Try escaping the strings like this:

$name = 'feedback';
$description = 'description';

//like this
echo '<input type="radio" onclick="show('. "'" . $name . "'" . ')">' . $description . '<br/>';

// or like this
echo "<input type=\"radio\" onclick=\"show(' . $name  . ')\">" . $description . "<br/>";

<script>
function show(name) {
  alert(name);
}
</script>

I hope this helps.