duandi1919 2013-05-20 11:17
浏览 14
已采纳

用javascript验证变量[关闭]

it is a code to submit several grades in one submission
this is the javascript code fore validation

function validateForm() {
    var x='<?php echo ($grade);?>';

    if (x>100) {
        alert("Invalid Data Entry");
        return false;
    }

it is not accessing the variable grade in the third echo down

<form name="form1" method="post" action="insertgradeac.php"onsubmit="return validateForm()" method="post">

<?php
    $con = mysql_connect($server, $username, $password);
    mysql_select_db($database);

    $query_fetch5 = "SELECT ass_class FROM assess WHERE ass_ID LIKE '$id'";
    $result_fetch5 = mysql_query($query_fetch5);
    $row5 = mysql_fetch_row($result_fetch5);
    $row5_0 = $row5[0];

    $query_fetch = "SELECT st_ID, st_name FROM student WHERE class_ID LIKE '$row5_0'";
    $result_fetch = mysql_query($query_fetch);

    while ($row = mysql_fetch_row($result_fetch)) {
        echo "<tr>
";

        echo "<td>$row[0]<input type=\"hidden\" name=\"stt_ID[]\" value=\"$row[0]\" /></td>
";
        echo "<td>$row[1]<input type=\"hidden\" name=\"student[]\" value=\"$row[1]\" /></td>
";
        echo "<td><input type=\"text\" name=\"grade[]\" /></td>
";
        echo "</tr>
";
    }


    mysql_close($con);
?>
  • 写回答

2条回答 默认 最新

  • doujia6433 2013-05-20 11:27
    关注

    That JS function will run in the browser, but it is trying to access a PHP variable that won't be set until after the form is submitted to the web server.

    Try this instead:

    function validateForm()
    {
      var grades = document.getElementsByName("grade[]");
      for (var i = 0; i < grades.length; i++) {
         if (Number(grades[i].value) > 100) {
            alert("Grades cannot be more than 100.");
            return false;
         }
      }
      return true;
    }
    

    I've used the getElementsByName() method to get a list of all of the grades[] elements, then I loop over them testing their values and displaying the alert if the value is no good.

    You don't actually say how you call validateForm(), but I assume you do so from the submit event of your form.

    Note that you should also add some code to confirm that the entered value is actually a number, and you need to do the same validation in your server-side PHP code in case a user has JS turned off (or uses browser dev tools to bypass your validation).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线