I have a code that submits a form when an option in a select box is clicked, but my problem is when I put it inside a loop, it doesn't work. Can you help me with it?
Here's the code:
<?php
$y1=5;
for($x1=1; $x1<=$y1; $x1++){
?>
<form name="myform[]" action="test.php" id ="myform" method="post">
<select id="sel_id" name="sel_name[]" onchange="submitform();">
<?php
$y=5;
for($x=1; $x<=$y; $x++){
?>
<option value="<?php echo $x;?>"><?php echo $x;?></option>
<?php
}
?>
</select>
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
<?php
}
?>
Now, I want every value of it be printed:
<?php
echo $_POST['sel_name'];
?>
You are using multiple form with same id="myform"
. this should be unique for every form.
Example:
<?php
$y1=5;
For($x1=1; $x1<=$y1; $x1++){
?>
<form name="myform[]" action="test.php" id ="myform_<?=$x1?>" method="post">
<select id="sel_id" name="sel_name[]" onchange="submitform(<?=$x1?>);">
<?php
$y=5;
For($x=1; $x<=$y; $x++){
?>
<option value="<?php echo $x;?>"><?php echo $x;?></option>
<?php
}
?>
</select>
</form>
<?php
}
?>
Your Java Script:
<script type="text/javascript">
function submitform(id)
{
document.getElementById("myform_"+id).submit();
}
</script>
Your test.php:
<?php
if(isset($_POST['sel_name']))
print_r($_POST['sel_name']);
?>
I am using different form ids as myform_<?=$x1?>
and also using this id into submitform()
function.
As per @Mr.Engineer, no need to use java script function submitform()
inside the for()
when you are using the unique IDs for form submission.
Just use this inside your function submitform()
:
document.getElementById("myform").submit();
EDIT : I didnt notice your for loop
You are using form in for loop, so you need separate id for each form.
So try this :
<?php
$y1=5;
for($x1=1; $x1<=$y1; $x1++){
?>
<form name="myform[]" action="test.php" id ="myform<?php echo $x1;?>" method="post">
<select id="sel_id<?php echo $x1;?>" name="sel_name[]" onchange="submitform(<?php echo $x1;?>);">
<?php
$y=5;
for($x=1; $x<=$y; $x++){
?>
<option value="<?php echo $x;?>"><?php echo $x;?></option>
<?php
}
?>
</select>
</form>
<?php } ?>
And outside of your for loop write your JS function :
function submitform(id)
{
document.getElementById("myform"+id).submit();
}
Please try below code for submit form using selectbox.
<select id="sel_id" name="sel_name[]" onchange="this.form.submit()">
...
</select>
Try to this may be it's help for you
$(field).closest("form").submit();
For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
$(this).closest("form").submit();
});