我在HTML页面上打印数据库内容,如下所示:
<form name="result_form" action="dostuff.php" onsubmit="return validateResult()" method="post">
<table>
<?php
$my_object_array = getStuffFromDatabase();
for ($x = 0; $x < count($my_object_array ); $x++) {
echo '<tr>';
echo '<td>';
echo 'Hemmalag: <input type="number" id="result' . $x. '" name="result' . $x . '" value = "' . $my_object_array[$x]->getResult(). '"></input>';
echo '</td>';
echo '</tr>';
}
?>
</table>
<button type="submit">Save</button>
</form>
我想使用javascript验证所有这些输入元素。这些字段将被检查为不为空。我不会使用必需的,因为Safari不支持它。我想的是:
form_validate.js:
function validateResult(){
var row_count = document.getElementById("row_counter").value;
var validate_success = true;
for (i = 0; i < row_count; i++) {
var tmp_home_result = document.getElementById("result" + i).value;
if(tmp_home_result == "" || tmp_home_result == null){
validate_success = false;
}
}
return validate_success;
}
但是,这似乎不起作用。表单仍然被发送到服务器。这里有什么问题?
答案 0 :(得分:1)
&#34; show_result_new_result_home_team&#34;你也需要把它给输入框。希望这会奏效。
我编辑了你的脚本并且它运行正常。请用这个。
function validateResult(){
var row_count = document.getElementById("row_counter").value;
for (i = 0; i < row_count; i++) {
var tmp_home_result = document.getElementById("result" + i).value;
if(tmp_home_result == "" || tmp_home_result == null){
return false;
}
}
return true;
}
答案 1 :(得分:0)
尝试validate.js jquery插件
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>