I have a form like this:
<form id="cars" action="file.php" method="post">
<a href="#" onclick="document.getElementById('cars').submit();"><input type="hidden" value="ford" name="model" />Ford</a>
<a href="#" onclick="document.getElementById('cars').submit();"><input type="hidden" value="toyota" name="model" />Toyota</a>
</form>
However, the $_POST['model']
gave error "Undefined index: model". What's wrong with that?
You only need to have one hidden input
outside your a
elements. It will get its value based on the element clicked just before submit()
. So your form will look like this:
<form id="cars" action="file.php" method="post">
<a href="#" onclick="submitModel('ford')">Ford</a>
<a href="#" onclick="submitModel('toyota')">Toyota</a>
<input id="hiddenModel" type="hidden" name="model" value="ford" />
</form>
And your javascript:
function submitModel(mdl) {
document.getElementById('hiddenModel').value = mdl;
document.getElementById('cars').submit();
}
I don't think your method will work as you desire. You need to rethink your approach to this. Why not just use links and querystrings?
Here is the simplest method I could come up trying to use your techniques as I supposed there is reason for you needing to do it this way:
<?php
if(isset($_POST['model']))
echo $_POST['model'];
?>
<script type="text/javascript">
function postBack(o) {
document.getElementsByName('model')[0].setAttribute("value", o);
document.getElementById('cars').submit();
}
</script>
<form id="cars" method="post">
<input type="hidden" name="model" />
<a href="javascript:void(0)" onclick="postBack('ford')">Ford</a>
<a href="javascript:void(0)" onclick="postBack('toyota')">Toyota</a>
</form>