I have this code -
<form method="post" action="generate.php">
<select name="test" id="Test">
<?php
$i=0;
foreach($testName as $name){
?>
<option value="<?php echo $name;?>"><?php echo $testName[$i];?></option>
<?php $i++; } ?>
</select>
<input type="submit" name="submit" value="Generate">
</form>
How I can store the value selected by user in a way that I can use it in the same php page?
Store the value in a hidden field with javascript/jquery like:
<input type="hidden" name="hidden" id="hidden">
and call an onchange
event on select element.
<select name="test" id="Test" onchange="test()">
Write corresponding js function,
<script>
function test()
{
var selectedval=$("#Test").val(); // get selected value
$("#hidden").val(selectedval); // set the value of hidden field
}
</script>
Store the value in a hidden field with javascript/jquery like:
<input type="hidden" name="hidden" id="hidden">
Write some jQuery Code to assign value to hidden field on change on drop down:
<script src="PATH/TO/JQUERY"></script>
<script>
$(function(){
$("#Test").live("change", function() {
$("#hidden").val($(this).val());
});
});
</script>
You can set an onchange handler to the form element to run javascript when the form option is selected. Here is an example (using your code):
<html>
<head>
</head>
<body>
<select name="test" id="Test" onchange="formChangeFunc(this)">
<?php
$i=0;
foreach($testName as $name)
{
?>
<option value="<?php echo $name;?>"><?php echo $testName[$i];?></option>
<?php
$i++;
}
?>
</select> <input type="submit" name="submit" value="Generate">
</form>
<script>
function formChangeFunc(sel) {
alert(sel.value);
document.getElementById('divIdToInsert').innerHtml(sel.value);
}
</script>
<div id="divIdToInsert"></div>
</body>
</html>
The example should give you an alert popup when you change the option. This should also insert the value into the specified div container.