I have a looping form in PHP that I want to submit through javascript. The problem is that each of the ids seem to need their own separate javascript submit code.
PHP CODE:
$i = 0;
while ($i < $num) {
$j = $i + 1;
echo "<form id='form".$j."' name='form3' method='post' action='post.php'>
<input type ='checkbox' name='box1' value = 'useless' > Useless</input>
<input type='submit' name= 'submit' id='submit' value='Submit' />
</form>";
$i++;
}
Javascript which doesn't work:
var x = 2;
var y = '<?php echo $num; ?>';
while (x <= y) {
$(document).ready(function () {
$("#form" + x).on("change", "input:checkbox", function () {
$("#form" + x).submit();
});
});
x++;
Since you are creating a submit button for each form but you seem to want to trigger the submit when the checkbox is changed, a simpler solution might be:
$('[name="box1"]').change(function() {
$(this).next().click();
});
// this is just here to demonstrate that all of the forms will not be submitted at once in response to your comment
$('form').submit(function(e){
e.preventDefault();
$('#result').append('submitted form with id '+ $(this).attr('id')+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" name="form1" method="post" action="post.php">
<input type="checkbox" name="box1" value="useless"/>Useless
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<form id="form2" name="form2" method="post" action="post.php">
<input type="checkbox" name="box1" value="useless"/>Useless
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<form id="form3" name="form3" method="post" action="post.php">
<input type="checkbox" name="box1" value="useless"/>Useless
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<br>
<div id="result"><div>
BTW, <input type ='checkbox' name='box1' value = 'useless' > Useless</input>
should be <input type ='checkbox' name='box1' value = 'useless' /> Useless
.
Input is a void element and does not have a closing tag
</div>