繁体   English   中英

当用户未在下拉菜单上选择选项时,如何提醒用户

[英]how do I alert user when they didn't select an option on a drop-down menu

我做了一个下拉菜单供用户选择,日期看起来像这样

在此处输入图片说明

我如何提醒用户他们没有选择日期? 月,日和年是<select>元素中的选项

if(document.forms[0].checkindate.selectedIndex == 1) {
    window.alert("You must select a date.");
    return false;
}

我这样做了,但是没用。

给选择值是空的,并通过使用html进行验证,例如

<select required>
   <option value="">Month</option>
   <option vslue="1">1</option>
</select>
<select required>
   <option value="">Day</option>
   <option vslue="1">1</option>
</select>
<select required>
   <option value="">Year</option>
   <option vslue="2016">2016</option>
</select>

或使用Javascript或jQuery验证

<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validate()
{

   if(document.getElementById("city").value=="-1")
    {
        alert('Please select a city');
        return false;
    }
    else if (document.getElementById('day').value=='')
    {
    alert('Please provide date for D.O.B');
    document.getElementById("day").style.borderColor="red";
    document.getElementById("day").style.backgroundColor="yellow";
    document.getElementById("day").style.borderWidth=2;
    return false;
    }
else if (document.getElementById('month').value=='')
    {
    alert('Please provide month for D.O.B');
    document.getElementById("month").style.borderColor="red";
    document.getElementById("month").style.backgroundColor="yellow";
    document.getElementById("month").style.borderWidth=2;
    return false;
    }
else if (document.getElementById('year').value=='')
{
    alert('Please provide year for D.O.B');
    document.getElementById("year").style.borderColor="red";
    document.getElementById("year").style.backgroundColor="yellow";
    document.getElementById("year").style.borderWidth=2;
    return false;
}
}
</script>
<body>
<form >
  City : <select id="city">
          <option value="-1">-~Select One~-</option>
          <option>City 1</option>
          <option>City 2</option>
          <option>City 3</option>
          <option>City 4</option>
          <option>City 5</option>
    </select>
    <br>

      Date of Birth:
Day
<input type="number" name="day" id='day' min="1" max="31" value="" required>
Month
<input type="number" name="month" min="1" id='month' max="12" value="" required>
Year
<input type="number" name="year" min="1950" id='year' max="2020" value="" required>


         <input type="submit" value="Login" onclick="return(validate());"
</form>
</body>
</html>

请参考上面给出的示例以清楚地了解。 希望你能理解。

您可以使用.each()函数来检查用户是否未选择任何下拉菜单。

$('select').each(function () { 
   if (this.value) 
      alert('value selected'); 
   else 
      alert('no selection'); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM