我有一個表單,我試圖在頁面提交之前檢查元素的顏色。我正在嘗試使用由'onsubmit ='使用函數調用的函數來驗證表單。如果我在下面的代碼中添加'document.getElementById(name).style.backgroundColor',當我提交頁面時,它將直接進入下一頁,而不詢問我是否想要進入下一頁或讓用戶知道表單有錯誤。它看起來像表單正在成功調用validate()和check_form()函數,但通過背景顏色檢查,似乎沒有完成validate()函數。我已經測試它沒有'style.backgroundColor',它工作正常(通知用戶)。我究竟做錯了什麼?檢查onsubmit上導致錯誤的元素的值
感謝
使用的代碼的簡化的例子:
function check_form(){
sample = document.getElementById(sample);
return 'false';
}
編輯:
<!DOCTYPE html>
<html>
<body>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="sample" name="sample" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
var sample = 'sample';
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
if(sample.style.backgroundColor == 'red'){
return 'false';
}
else{
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
check_form函數,它工作的試驗比如我的方式我現在設置的表單更精確地顯示爲:
<!DOCTYPE html>
<html>
<body>
<?php $sample = 'test'; ?>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="<?php echo $sample;?>" name="<?php echo $sample;?>" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
sample = <?php echo json_encode("$sample"); ?>;
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
當樣本是從另一個頁面帶來的動態創建的形式。
使用報價; – Saty
http://jsfiddle.net/arunpjohny/7a2jp454/2/ –