Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to get dropdown selected value in javascript variable.When I change dropdown value the alert is displaying the value correctly and I'm getting that value using getElementById in the textbox and the textbox displaying the selected value.But outside script I am unable to get the selected value.If I echo the value it is displaying '"+javavar+"'.

XML
<script>
function selecttext()
{
var javavar=document.getElementById("text").value;

document.getElementById("text1").value="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
</script>
<?php
echo $phpvar;
?>
<body>
<select name="text" id="text" onchange="return selecttext();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" id="text1" name="text1">
</body>



Please give any Suggestions.
Posted
Updated 4-Feb-15 22:58pm
v3
Comments
Nathan Minier 5-Feb-15 7:26am    
Okay, so, this code cannot work. <?php> tags are used on the server, in a PHP context, when assembling the page, they will not show in the source of an assembled page on a client browser, because browsers can't do anything with php tags.

JavaScript, on the other hand, is part of the markup and is used by the browser. You can use PHP to build JavaScript variables, like so:
<script type="text/javascript">
<?php echo "var javascriptVar = " + $phpVar + ";" ?>
</script>

Since the JavaScript is executed on the browser and the PHP isn't, though, you cannot access PHP at runtime of the JavaScript. That's why your construct there could never work. To interact with PHP again you'd need to postback or send an AJAX request, send information back to the PHP for processing, and return a result to the browser that the JavaScript can parse.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900