0

我想做一个测验。首先我做一个测验插入。所以我想做一个验证,比如填写表单中的所有值,答案必须在选项中......我用 codeigniter 框架尝试它。这是我的观点

<?php include_once('header.php'); ?>
<?php include_once('tnavbar.php'); ?>

<script src="<?php echo base_url();?>/js/jquery-1.9.1.min.js"></script>
<script>
function validateForm1()   //This javascript function is not working
{
var j=<? echo $number;?>;
for(var i=1; i<= j ; i++)
var qus1=document.forms["myForm1"]["ques[i]"].value;
var opt1=document.forms["myForm1"]["opt1[i]"].value;
var opt2=document.forms["myForm1"]["opt2[i]"].value;
var opt3=document.forms["myForm1"]["opt3[i]"].value;
var ans1=document.forms["myForm1"]["ans1[i]"].value;
if ((qus1==null || qus1=="")||(opt1==null || opt1=="")||(opt2==null || opt2=="")||        (opt3==null || opt3=="")||(ans1==null || ans1==""))
  {
  alert("All field must be fill");
  return false;
  }
}
</script>

<div class="maincontent_area">
<div class="container">
    <div class="row">
        <div class="span12">
        <form name="myForm1" action="<? echo base_url()."/index.php/Tmcq_test/insertmcq";?>" onsubmit="return validateForm1()" method="post">


            <?php         for($i=1; $i<= $number; $i++){
//Here the $number is user input like 2,3, or 4 etc number of mcq
?>
   Question : <input type="text" name="ques[<?php echo $i;?>]"><br/>
   Option 1 : <input type="text" name="opt1[<?php echo $i;?>]" ><br/>
   Option 2 : <input type="text" name="opt2[<?php echo $i;?>]" ><br/>
   Option 3 : <input type="text" name="opt3[<?php echo $i;?>]" ><br/>
   &nbsp;Answer : &nbsp;<input type="text" name="ans[<?php echo $i;?>]" ><br/>

   <br/>
   <?php  //echo $value->answer;

    } ?>
                    <input type="hidden" name="quiz_name"  value="<?php echo $name;?>">
                    <input type="hidden" name="sub_id"  value="<?php echo $sub_id;?>">
                    <input type="hidden" name="quiz_number"  value="<?php echo $number;?>">
                    <input type="hidden" name="time_number"  value="<?php echo $time_number;?>">

        <input type="submit" name="submit" id="submit" value="Create"  class="btn btn-info">


        </form>


        <a href="<? echo base_url()."/index.php/Tmcq_test";?>"> <button class="btn btn-info"> Exit  </button> </a>

        </div>
    </div>
</div>

现在如何使用 javascript 在此视图中添加表单验证我添加了一些 js 代码但它不起作用所以我如何实现它?谁能帮忙

4

1 回答 1

0

您应该更新您的变量分配。在您的情况下,JS 正在寻找名为“ques[i]”、“opt1[i]”、“ans1[i]”等的表单元素。但是您需要将字母“i”设置为变量。试试这个:

var qus1=document.forms["myForm1"]["ques[" + i + "]"].value;
var opt1=document.forms["myForm1"]["opt1[" + i + "]"].value;
var opt2=document.forms["myForm1"]["opt2[" + i + "]"].value;
var opt3=document.forms["myForm1"]["opt3[" + i + "]"].value;
var ans1=document.forms["myForm1"]["ans1[" + i + "]"].value;    

这对我有用:http: //jsfiddle.net/kXwBr/1/

于 2013-09-04T14:50:04.720 回答