简体   繁体   中英

Passing php variable to button onclick function

I am a newbie working on a screen which has a conditional button which should appear only if $step==2. In this case, the button is shown and on click, redirects me to another page within my project. However, the url to which it should redirect me is not fixed, but has a parameter within it. I am having trouble getting the onclick to work!

I have tried defining a $path variable in which I store the relocation string. I do this in the following way:

<?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>

When I echo this $path, I get exactly the string I need, which is:

"window.location='{{ url("/location/2/description") }}'"

(Note: The $location->id in my test case is 2)

However, I then try using this $path for the onclick of the button and it's not working! Here is the whole thing:

<?php if ($step == 2) : ?>
  <?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>
  <button class="button_s_red" onclick=<?php echo $path; ?>>{{ trans('setup_process.STEP2_Button') }}</button>
<?php endif; ?>

When I inspect this button in chrome, it seems that on the onclick, the / character is not getting through. But this is odd since when I echo the $path I do get this character, and / doesn't seem to be an escape character from what I've googled.

I've tried pretty much everything and googled every possible help but can't seem to make it work! Thanks in advance for your help!

id.'/description") }}\\'"'?> >{{ trans('setup_process.STEP2_Button') }}

I think u must use " in Your code like this.

<?php if ($step == 2) : ?>
  <?php $path = '"window.location=\'{{ url("/location/'.$location->id.'/description") }}\'"'?>
  <button class="button_s_red" onclick=("<?php echo $path; ?>")>{{ trans('setup_process.STEP2_Button') }}</button>
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM