Betty
Betty

Reputation: 29

get the value of a php variable in an input using javascript

I want to concatenate the value of my variable $variable with the value of my input using javascirpt

$variable= file_get_contents('./env.txt');

<select id="customer_id" name="customer_id" w300 required pj-chosen" data-msg-required="<?php __('lblFieldRequired');?>" onchange="document.getElementById('title').value=this.value + 'P' + **$variable**">
...
                    <input type="text" name="title" id="title" class="pj-form-field w400 required" data-msg-required="<?php __('lblFieldRequired');?>" data-msg-remote="<?php __('lblTitleUsed');?>"  value=""><script></script>

Upvotes: 0

Views: 671

Answers (2)

Peter Pointer
Peter Pointer

Reputation: 4162

Ok so why not echo out the variable?

PHP:

onchange="document.getElementById('title').value=this.value + 'P' + '<?php echo addslashes($variable) ?>'">

The addslashes call will escape quotes against security problems.

If $variable does not change a more elegant way is to make the $variable a JavaScript variable and then use it normally. This makes the JavaScript part more readable, but of course other programmers will have to be aware that you add that variable via PHP.

PHP:

// somewhere at the beginning of your body tag:
<script>
  window.variable = '<?php echo addslashes($variable) ?>';
</script>

HTML:

<... onchange="document.getElementById('title').value=this.value + 'P' + window.variable" />

I wrote this off the top of my head - please tell if this worked as I intended.

Upvotes: 2

ADyson
ADyson

Reputation: 61784

On the line below you've already got some PHP inline in the HTML, outputting values into those data attributes.

For $variable you can follow much the same pattern as that, except you'll need to explicitly echo the variable so it gets embedded into the JavaScript (I assume those other functions echo within them, removing the need for another one):

onchange="document.getElementById('title').value=this.value + 'P' + '<?php echo addslashes($variable); ?>'"

Upvotes: 1

Related Questions