2014-08-28 78 views
0

玉傢伙的錯誤消息,我已經做了一些研究和不能找到一些作品來解決我的問題,即使我敢肯定它的一個簡單的修補程序:)當添加特定的下拉選項中選擇

我有一個簡單的聯繫表單,其中第一行是一個下拉選擇。此下拉列表確定表單提交給哪位員工。我只想讓我的默認選項「請選擇類別」返回一條錯誤消息,以便提交者必須返回並選擇其中一個選項以獲取發送的表單。當沒有選擇任何東西時,它會創建大量垃圾郵件到默認電子郵件。

這裏是下拉的碼位:

   <tr> 
      <td><label for="sendTo">Category (required):</label></td> 
      <td> 
       <select id="sendTo" name="sendTo"> 
        <option id="pleaseSelectcategory1" value="pleaseSelectcategory1">Please Select Category</option> 
        <option id="aftermarketCustomerservice" value="aftermarketCustomerservice">Aftermarket Customer Service</option> 
        <option id="technicalAssistance" value="technicalAssistance">Technical Assistance</option> 
        <option id="aftermarketSales" value="aftermarketSales">Aftermarket Sales</option> 
        <option id="performanceProducts" value="performanceProducts">Performance Products & Sales</option> 
        <option id="oemSales" value="oemSales">OEM Sales</option> 
        <option id="exportSales" value="exportSales">Export Sales</option> 
        <option id="generalFeedback" value="generalFeedback">General Feedback</option> 
       </select> 
      </td> 
      </tr> 

我只需要放什麼東西在我的HTML,如果有的話,使這個錯誤信息會出現在我的PHP文件。提前致謝!!

+0

'if($ _ POST ['sendTo'] ==「pleaseSelectcategory1 「){//}' – 2014-08-28 13:44:45

+0

使用Javascript來處理這將避免無用的服務器交換。只是谷歌「表單驗證與JavaScript」。 (這並不意味着稍後再仔細檢查服務器端是不是很好btw) – Sugar 2014-08-28 13:53:15

+0

@ Fred-ii-這似乎阻止電子郵件,但我將如何提醒人們選擇該類別讓它正確發送? – 2014-08-28 14:10:01

回答

0

在純JavaScript,你可以使用下面的功能:

function checkCategory(){ 
    if(document.getElementById('sendTo').value === 'pleaseSelectcategory1') { 
    alert("You need to select category"); 
    //This is to ensure that the form doesn't get submitted. 
    return false; 
    } 
} 

要麼上的按鈕或窗體本身使用onclick="javascript:checkCategory();"onsubmit="javascript:checkCategory();"

在PHP中你可以使用:

if($_POST['sendTo'] == "pleaseSelectcategory1") 
{ 
    //However you want to handle the the fact the user selected the option 
} 
1

在發佈數據之前,您應該使用Javascript函數來驗證您的表單。這對UX來說更好,並且會阻止表單甚至到達PHP post函數。

在您的形式有onsubmit領域調用JavaScript函數:

<form name="form" id="form" action="" onsubmit="return validateForm()" method="POST"> 

和檢查選擇框的值你的Javascript功能:

// Basic form validation for select box. 
function validateForm() { 
    if (document.getElementById("sendTo").value != null && docmument.getElementById("sendTo").value != "pleaseSelectcategory1") { 
     return true; 
    } 

    //Handle error message here. 
    alert("Please select a category"); 
    return false; 
} 

您也可以驗證表單一旦形式獲取張貼在PHP與:

if ($_POST['sendTo'] === 'pleaseSelectcategory1') { 
    // Redirect back to form or do whatever 
} 
+0

我添加了所有這些位,並且表單仍然發送並且「請選擇類別」字段被選中並落在我的郵件中。我缺少一些東西:| – 2014-08-28 14:40:07

+0

檢查你的Javascript函數是否被調用,方法是把'alert(document.getElementById(「sendTo」).value);'正好在'validateForm()'中的if語句的上面,看看是否正在調用函數,2.來自選擇框的值正在被正確地檢索。 – eluong 2014-08-28 14:46:30

相關問題