2015-11-28 76 views
-2

我在PHP中有一个循环表单,我想通过javascript提交。问题是,每个ID似乎都需要他们自己的单独的JavaScript提交代码。set javascript div id to increasing var

PHP代码:

$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' >&nbsp;Useless</input> 
    <input type='submit' name= 'submit' id='submit' value='Submit' /> 
    </form>"; 
    $i++; 
} 

的Javascript不工作:

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++; 
+0

你需要增加你的while循环中的X,如果控制台日志这是是一个无限循环,但在相同的元素。 – David

+0

php在js中?你怎么称呼js功能?什么样的预期结果?你目前的结果是什么? –

回答

0

因为要创建一个为每个表单提交按钮,但你似乎想触发提交时的复选框更简单的解决方案可能是:

$('[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>

顺便说一句,<input type ='checkbox' name='box1' value = 'useless' >&nbsp;Useless</input>应该是<input type ='checkbox' name='box1' value = 'useless' />&nbsp;Useless

输入是void element并没有关闭标签

+0

但它然后会提交​​所有的循环表格,这不是唯一的值被提交有一个隐藏的变量值,当发布时将只更新提交表单的mysql列。如果我像你所建议的那样做,它会更新所有这些(27),而不仅仅是一个。 – Celeste

+0

@Celeste这是不正确的,提交按钮是在一个表单内,当单击该按钮时,它只会提交父表单,它不会提交其他26个表单。我已经更新了我的答案,以证明这个 – DelightedD0D

+0

提交按钮没有触发JavaScript,它将它发送到post.php – Celeste