當前,如果用戶離開鍛鍊標題輸入空白並在鍛鍊文本中有文本輸入,則會顯示一條提示,告訴用戶填寫完整表單,反之亦然。當警報出現並按下OK時,表單數據將丟失,用戶必須重新添加所有輸入。我將如何使警報顯示,並按下ok使用戶保持在同一頁面上?我不確定它是否因爲我點擊「創建新練習」或其他內容而隱藏並顯示div。確認警告仍保留在同一頁面上
我的代碼如下
CourseA.php
HTML:
<script>
function showDiv(el1,el2){
document.getElementById(el1).style.display = 'block';
document.getElementById(el2).style.display = 'none';
}
</script>
<div class="right">
<h2 id = 'course_admin_titleA'>Course A</h2>
<button id= 'create_btnA' onClick="showDiv('is', 'ie')">Create new session</button>
<button id= 'create_btnB' onClick="showDiv('ie', 'is')">Create new exercise</button>
</div>
<div id= "ie">
<!-- input form for admin -->
<form action="courseA.php" method="post" enctype="multipart/form-data">
<table class ="table_exercise">
<td id = "exercise_titles"><strong> Exercise Title:</strong></td>
<td><input type="text" name="exercise_title" value="<?php if(isset($_SESSION['a'])){echo $_SESSION['a'];} ?> " size="60" /></td>
</tr>
<tr>
<!-- input text area for admin to type exercise content -->
<td id = "exercise_titles"><strong> Exercise Text:</strong></td>
<td><textarea name="exercise_text" rows="15" cols="50" ><?php if(isset($_SESSION['b'])){echo $_SESSION['b'];} ?></textarea></td>
</tr>
</table>
<!-- button with input type 'submit' which is referenced by the php code -->
<button id= 'create_btnB'input type="submit" name="submit1" > Publish Exercise Now</button>
<!-- Hide if not clicked -->
<input type="hidden" value="ie" name="type">
</form>
</div>
PHP:
<?
session_start();
//if submit button is set i.e 'publish exercise now' pressed then:
if(isset($_POST['submit1'])){
$_SESSION['a'] = $_POST['exercise_title']; //assign to session variable
$_SESSION['b'] = $_POST['exercise_text'];
//local variables taking the input names from the html forms above
$exercise_title = $_POST['exercise_title'];
$exercise_text = $_POST['exercise_text'];
//validation
if($exercise_title =='' OR $exercise_text==''){
echo "<script>alert('Please make sure the exercise has a title and exercise info')</script>";
//exit();
} else {
//query to insert the form data from the admin into the exercises table
$insert_exercises = "insert into exercises (exercise_title,exercise_text)
values ('$exercise_title','$exercise_text')";
//runs query
$run_exercises = mysqli_query($con,$insert_exercises);
//JS to tell user exercise has been published
echo "<script>alert('Exercise Has been Published!')</script>";
//returns to courseA page on the admin panel
echo "<script>window.open('courseA.php','_self')</script>";
} //end of else
} //end of IF
//end of if & end of PHP
} ?>
感謝
是的,它是代碼說的。建議您使用JavaScript驗證表單,而不是使用PHP。您在此使用PHP(表單在您提交數據時驗證)來驗證您的表單。 – divy3993
你不能單單信任JavaScript來進行表單驗證。無論如何,你將不得不在PHP中進行驗證。 – harris
你在php文件裏面使用這個html嗎? –