2012-11-05 19 views
1

我有一系列使用php動態創建的表單。更改表單名稱的表單驗證

表單名稱是使用php $ formcount變量創建的,並使用while循環遞增。因此,對於創建的多個表單,表單名稱將爲: update1 update2 update3等。

我有一個下拉菜單在每個表單需要驗證。我無法成功使用JavaScript來單獨驗證每個表單,因爲表單的名稱每次都在更改。

$formcount=0; 
while($info=mysql_fetch_array($agent_q)) 
{ 
...... 
echo(' 
<form name="update'.$formcount.'" method="post" onsubmit="return CheckUpdate(this);"> 
<select name="login_time" id="login_time"> 
<option value="none">Select Login</option> 
<option value="00:30">00:30</option> 
<option value="02:30">02:30</option> 
<option value="03:30">03:30</option> 
<option value="04:30">04:30</option> 
<option value="06:30">06:30</option> 
<option value="09:30">09:30</option> 
<option value="12:30">12:30</option> 
<option value="13:30">13:30</option> 
<option value="16:30">16:30</option> 
<option value="17:30">17:30</option> 
<option value="18:30">18:30</option> 
<option value="19:30">19:30</option> 
<option value="20:30">20:30</option> 
<option value="21:30">21:30</option> 
<option value="22:30">22:30</option> 
</select></form>'); 
..... 
} 

我的JS是

function CheckUpdate(){ 
    if(document.????==0){ 
    alert("Select Login Time!\r\n"); 
    return false; 
    } 
    else 
    return true; 
} 

不知道要放什麼東西到位???的。我相信這是相當簡單的..任何幫助都非常感謝。謝謝!

回答

1

有幾種方法來處理它。可能最直接的(不必修改現有的PHP)將使用form.elements集合。在你的情況下,<select>elements[0]

// The form node is passed in the function call as (this) 
function CheckUpdate(node){ 
    // The first form element in the form node passed to the function is the <select> 
    // Test that a value other than the default is selected... 
    if (node.elements[0].value == 'none'){ 
     alert("Select Login Time!\r\n"); 
     return false; 
    } 
    else return true; 
} 

還有其他的方法來管理這一點。例如,如果總是隻有<form>內一個<select>,但不一定在第一位置[0],你可以使用getElementsByTagName()檢索它作爲當前<form>

function CheckUpdate(node){ 
    var selNodes = node.getElementsByTagName('select'); 
    // Check the value of the first <select> child of the <form> (which was passed as node) 
    if (selNodes[0].value == 'none'){ 
     alert("Select Login Time!\r\n"); 
     return false; 
    } 
    else return true; 
} 

注意的子:在你的PHP循環,你是重複<select> id屬性。這是不允許的 - id屬性應該是唯一的。你可以追加你的$formcount

echo ' 
<form name="update'.$formcount.'" method="post" onsubmit="return CheckUpdate(this);"> 
<select name="login_time" id="login_time' . $formcount . '"> 
...; 
+0

有一個以上的輸入字段的形式,選擇在第四位......所以我嘗試node.elements [3] .value的==「無',工作非常好:)。我不需要選擇id屬性,因爲它沒有達到任何目的,所以我刪除了它。 是否有一個選項可以獲取所有在表單函數中發送的所有轉儲?我知道有一個在PHP中:var_dump($ _ POST) – Chinnappa

0

試試這個

<form name="update'.$formcount.'" id="update'.$formcount.'" method="post" onsubmit="return CheckUpdate(this);"> 

function CheckUpdate(form){ 
    if(document.form.login_time.value == 0){ 
    alert("Select Login Time!\r\n"); 
    return false; 
    } 
    else 
    return true; 
} 
+0

試過但沒有工作.. – Chinnappa