将javascript div id设置为增加var

时间:2015-11-28 02:52:23

标签: javascript php jquery variables auto-increment

我在PHP中有一个循环表单,我想通过javascript提交。问题是每个id似乎都需要自己独立的javascript提交代码。

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

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
$('[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>');
});
&#13;
<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>
&#13;
&#13;
&#13;

BTW,<input type ='checkbox' name='box1' value = 'useless' >&nbsp;Useless</input>应为<input type ='checkbox' name='box1' value = 'useless' />&nbsp;Useless

输入为void element且没有结束标记