选择特定下拉选项时添加错误消息


Adding error message when a specific drop down option is selected

好吧,伙计们,我做了一些研究,但找不到能解决我问题的方法,尽管我确信这是一个简单的解决方案:)

我有一个简单的联系表格,其中第一行是下拉选择。这个下拉列表决定了表单提交给哪个员工。我只想让我的默认选项"请选择类别"返回一条错误消息,以便提交者必须返回并选择其中一个选项来发送表单。当没有选择任何内容时,它会向默认电子邮件创建大量垃圾邮件。

这是代码的下拉部分:

                <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文件中。提前感谢!!

在发布数据之前,您应该使用Javascript函数来验证表单。这对用户体验更好,甚至会阻止表单到达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
}

在纯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
}